工厂模式
抽象动物:
java
public abstract class Animal {
// 动物都要吃饭
public abstract void eat();
}
java
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("小猫吃猫粮");
}
}
java
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("小猫吃猫粮");
}
}
抽象工厂:
java
public abstract class AnimalFactory {
public abstract Animal createAnimal();
}
java
public class CatFacoty extends AnimalFactory{
@Override
public Animal createAnimal() {
return new Cat();
}
}
java
public class DogFactory extends AnimalFactory{
@Override
public Animal createAnimal() {
return new Dog();
}
}
java
public class FactoryTest {
public static void main(String[] args) {
AnimalFactory factory = new DogFactory();
Animal animal = factory.createAnimal();
animal.eat();
AnimalFactory factory2 = new CatFacoty();
Animal animal2 = factory2.createAnimal();
animal2.eat();
}
}
在这里,如果需要创建新的类,只需要新增animal的子类和factory的资料,不需要修改原来的代码,对扩展开放,符合开闭原则。
源码参考:
- Collection.iterator
- URLStreamHandler.createURLStreamHandler