// public static Dog createDog() {
// return new Dog();
// }
//
// public static Cat createCat() {
// return new Cat();
// }
public static Animal createAnimal(String type) {
if ("dog".equals(type)) {
return new Dog();
} else if ("cat".equals(type)) {
return new Cat();
} else {
return null;
}
}
}
public class AnimalDemo {
public static void main(String[] args) {
// 具体类调用
Dog d = new Dog();
d.eat();
Cat c = new Cat();
c.eat();
System.out.println("------------");
// 工厂有了后,通过工厂给造
// Dog dd = AnimalFactory.createDog();
// Cat cc = AnimalFactory.createCat();
// dd.eat();
// cc.eat();
// System.out.println("------------");
// 工厂改进后
Animal a = AnimalFactory.createAnimal("dog");
a.eat();
a = AnimalFactory.createAnimal("cat");
a.eat();
// NullPointerException
a = AnimalFactory.createAnimal("pig");
if (a != null) {
a.eat();
} else {
System.out.println("对不起,暂时不提供这种动物");
}
}
}
2:工厂方法模式
这个工厂,面向接口编程。抽象类。
有大工厂,许多小工厂。需要什么工厂,造什么工厂。需要猫,就造猫,需要狗,就造狗。
工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。
优点: 客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性
缺点 :需要额外的编写代码,增加了工作
public interface Factory {
public abstract Animal createAnimal();
}
public class DogFactory implements Factory {
@Override
public Animal createAnimal() {
return new Dog();
}
}
public class CatFactory implements Factory {
@Override
public Animal createAnimal() {
return new Cat();
}
}
public class AnimalDemo {
public static void main(String[] args) {
// 需求:我要买只狗
Factory f = new DogFactory();
Animal a = f.createAnimal();
a.eat();
System.out.println("-------");
//需求:我要买只猫
f = new CatFactory();
a = f.createAnimal();
a.eat();
}
}