问题
典型的接口和实现类如下,我们要根据相应的需求创建出不同的对象。
public interface Animal {
void say();
}
public class Cat implements Animal {
public void say() {
System.out.println("I am a cat");
}
}
public class Dog implements Animal {
public void say() {
System.out.println("I am a dog");
}
}
简单工厂
public class AnimalFactory {
public static Animal createAnimal(String animal) {
if (animal.equals("Dog")) {
return new Dog();
}else if (animal.equals("Cat")) {
return new Cat();
}
return null;
}
}
public class Client {
public static void main(String[] args) {
Animal cat = AnimalFactory.createAnimal("Cat");
Animal dog = AnimalFactory.createAnimal("Dog");
}
}
简单工厂其实就是:传入一个对象的标识,然后根据标识创建对象。这个方法实现简单,但是如果再添加一个Bird类,需要创建Bird对象的话则需改动AnimalFactory方法。
工厂方法
public interface Factory {
Animal createAnimal();
}
public class CatFactory implements Factory{
public Animal createAnimal() {
return new Cat();
}
}
public class DogFactory implements Factory {
public Animal createAnimal() {
return new Dog();
}
}
public class Client {
public static void main(String[] args) {
Animal cat = new CatFactory().createAnimal();
Animal dog = new DogFactory().createAnimal();
}
}
工厂方法如上,即使当需要添加一个Bird时,同时创建BirdFactory即可在客户端中使用,而不用改动到其它代码。
抽象工厂
这个设计到一个产品族的概念,Cat,Dog是分为不同家的。我要么统一买A家的Cat,Dog,要么统一买B家的。
public interface Animal {
void say();
}
//A家产品
public class CatA implements Animal {
public void say() {
System.out.println("I am a cat from A");
}
}
public class DogA implements Animal {
public void say() {
System.out.println("I am a dog from A");
}
}
//B家产品
public class CatB implements Animal {
public void say() {
System.out.println("I am a cat from B");
}
}
public class DogB implements Animal {
public void say() {
System.out.println("I am a dog from B");
}
}
public interface Factory {
Animal createCat();
Animal createDog();
}
public class FactoryA implements Factory {//A家工厂
public Animal createCat() {
return new CatA();
}
public Animal createDog() {
return new DogA();
}
}
public class FactoryB implements Factory {//B家工厂
public Animal createCat() {
return new CatB();
}
public Animal createDog() {
return new DogB();
}
}
public class Client {
public static void main(String[] args) {
Factory factoryA = new FactoryA();
Animal catA = factoryA.createCat();
Animal dogA = factoryA.createDog();
}
}
抽象工厂如上,创建一个A工厂,从A工厂生产出来的都是A家的产品,避免了产品创建之间的混乱。