黑马程序员技术交流社区
标题: 【南京校区】Java设计模式之抽象工厂 [打印本页]
作者: 大蓝鲸小蟀锅 时间: 2019-1-11 13:31
标题: 【南京校区】Java设计模式之抽象工厂
抽象工厂意图提供一个接口,用于创建相关或从属的一类对象,而不指定它们的具体类。
解释真实世界的例子
创建一个王国,我们需要对象的共同主题。精灵王国需要精灵王,精灵城堡和精灵的军队而兽人王国需要一个兽人王,兽人和兽人军队的城堡。在王国中对象间的依赖
字面意思
工厂的工厂;把个体和相关的、依赖的工厂组合在一起而不指定具体的工厂。
维基百科
抽象工厂模式提供了一种方法来封装一组具有共同主题的工厂,而不指定具体的类。
编程例子
翻译上面的王国例子。首先,我们为王国中的对象提供了一些接口和实现。
public interface Castle {
String getDescription();
}public interface King {
String getDescription();
}public interface Army {
String getDescription();
}
// Elven implementations ->public class ElfCastle implements Castle {
static final String DESCRIPTION = "This is the Elven castle!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}public class ElfKing implements King {
static final String DESCRIPTION = "This is the Elven king!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}public class ElfArmy implements Army {
static final String DESCRIPTION = "This is the Elven Army!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
然后我们王国工厂的抽象和实现
public interface KingdomFactory {
Castle createCastle();
King createKing();
Army createArmy();
}
public class ElfKingdomFactory implements KingdomFactory {
public Castle createCastle() {
return new ElfCastle();
}
public King createKing() {
return new ElfKing();
}
public Army createArmy() {
return new ElfArmy();
}
}
public class OrcKingdomFactory implements KingdomFactory {
public Castle createCastle() {
return new OrcCastle();
}
public King createKing() {
return new OrcKing();
}
public Army createArmy() {
return new OrcArmy();
}
}
现在我们有了一个抽象工厂,让我们制造相关的家族,即精灵王国工厂制造精灵城堡、国王和军队等。
KingdomFactory factory = new ElfKingdomFactory();
Castle castle = factory.createCastle();
King king = factory.createKing();
Army army = factory.createArmy();
castle.getDescription(); // Output: This is the Elven castle!
king.getDescription(); // Output: This is the Elven king!
army.getDescription(); // Output: This is the Elven Army!
适用范围· 一个系统应该独立于它的产品是如何创建、组合和表示。
· 一个系统应配置一个产品的多种家族
· 一系列相关产品对象被设计为一起使用,您需要强制执行此约束。
· 您希望提供一个产品类库,并且希望只显示它们的接口,而不是它们的实现。
· 依赖的生命周期短于消费的一方。
· 你需要一个运行时的值来构造一个特殊的依赖
· 你要决定哪些产品在运行时调用哪种家族.
· 在解析依赖项之前,您需要提供一个或多个参数,这些参数只在运行时已知。
用例:· 选择要在运行时调用文件服务、数据库服务或网络服务适当的实现.
· 更好的实现单元测试
结论:· 依赖注入可以让java运行时报错的服务提早在编译时被抓住.
现实世界的例子权威信息
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |