AbstractFactory模式就是用来解决这类问题的:要创建一组相关或者相互依赖的对象。
AbstractFactory模式典型的结构图:
假设:有若干骨头和鱼残渣, 需要狗和猫处理。 因此这种情况下,猫和狗是一起协同工作。
AbstractFactory模式关键就是将这一组对象的创建封装到一个用于创建对象的类中,维护这样一个创建类总比维护n多相关对象的创建过程要简单的多。
代码:
IAbstractFactory:
public interface IAbstractFactory { Dog createDog() ; Cat createCat() ; }
CreateFactoryBlack:
public class CreateFactoryBlack implements IAbstractFactory { @Override public Dog createDog() { return new BlackDog(); } @Override public Cat createCat() { return new BlackCat(); } }
CreateFactoryWhite:
public class CreateFactoryWhite implements IAbstractFactory { @Override public Dog createDog() { return new WhiteDog(); } @Override public Cat createCat() { return new WhiteCat(); } }Cat:
public interface Cat { void eatFish() ; }WhiteCat:
public class WhiteCat implements Cat { @Override public void eatFish() { System.out.println("White Cat eat fish"); } }BlackCat:
public class BlackCat implements Cat { @Override public void eatFish() { System.out.println("Black Cat eat fish"); } }Dog:
public interface Dog { void bitBone() ; }WhiteDog:
public class WhiteDog implements Dog { @Override public void bitBone() { System.out.println("White Dog bit bone"); } }
BlackDog:
public class BlackDog implements Dog { @Override public void bitBone() { System.out.println("Black Dog bit bone"); } }
AbstractFactoryTest:
public class AbstractFactoryTest { public static void main(String[] args) { IAbstractFactory factory1 = new CreateFactoryWhite() ; factory1.createCat().eatFish() ; //White Cat eat fish factory1.createDog().bitBone() ; //White Dog bit bone IAbstractFactory factory2 = new CreateFactoryBlack() ; factory2.createCat().eatFish() ; //Black Cat eat fish factory2.createDog().bitBone() ; //Black Dog bit bone } }
区别:
AbstractFactory模式是为创建一组(有多类)相关或依赖的对象提供创建接口;
Factory模式正如我在相应的文档中分析的是为一类对象提供创建接口或延迟对象的创建到子类中实现。