GOF经典设计模式 - Abstract Factory 抽象工厂
GOF Design Pattern定义
提供一个创建一系列相关或相互依赖对象的接口,而无需指定他们具体的类。[DP]
类图
代码示例
创建Factory接口、产品接口
public interface Factory {
Head getHead();
Hand getHand();
Foot getFoot();
}
public interface Foot {
}
public interface Hand {
}
public interface Head {
}
实现Factory,这里只贴出一个例子
public class HorseFactory implements Factory {
public Head getHead() {
return new HorseHead();
}
public Hand getHand() {
return new HorseHand();
}
public Foot getFoot() {
return new HorseFoot();
}
}
实现产品,同样只贴出一个例子
public class HorseHead implements Head {
}
public class HorseHand implements Hand {
}
public class HorseFoot implements Foot {
}
client代码
public class Client {
public static void main(String[] args) {
Factory factory = new DogFactory();
factory.getFoot();
factory.getHand();
factory.getHead();
factory = new CowFactory();
factory.getFoot();
factory.getHand();
factory.getHead();
factory = new BullFactory();
factory.getFoot();
factory.getHand();
factory.getHead();
factory = new HorseFactory();
factory.getFoot();
factory.getHand();
factory.getHead();
}
}
应用场景
后续补充....