【黑马程序员济南中心】工厂设计模式-抽象工厂模式
今天咱们讲一讲工厂设计模式的最后一种:抽象工厂模式。这个至关于工厂设计模式的进阶版本,咱们能够先去了解它,在慢慢的熟练使用它。程序员
什么是抽象工厂模式?抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂建立其余工厂。该超级工厂又称为其余工厂的工厂。这种类型的设计模式属于建立型模式,它提供了一种建立对象的最佳方式。设计模式
在抽象工厂模式中,接口是负责建立一个相关对象的工厂,不须要显式指定它们的类。每一个生成的工厂都能按照工厂模式提供对象。spa
咱们用一个类图来展现抽象工厂模式:设计
首先要建立一个接口,这个接口就是指的Creator,而一组相关或者相互依赖的对象,就是指的ProductA和ProductB以及它们具体的实现类,咱们返回的接口或者抽象类则是指的ProductA和ProductB接口。对象
咱们用代码体现:接口
工厂类:产品
public interface Creator {class
ProductA createProductA();进阶
ProductB createProductB();程序
}
工厂实现类:
public class ConcreteCreator1 implements Creator {
public ProductA createProductA() {
return new ProductA1();
}
public ProductB createProductB() {
return new ProductB1();
}
}
public class ConcreteCreator2 implements Creator {
public ProductA createProductA() {
return new ProductA2();
}
public ProductB createProductB() {
return new ProductB2();
}
}
产品类:
interface ProductA {
void methodA();
}
interface ProductB {
void methodB();
}
产品实现类:
class ProductA1 implements ProductA {
public void methodA() {
System.out.println("产品A系列中1型号产品的方法");
}
}
class ProductA2 implements ProductA {
public void methodA() {
System.out.println("产品A系列中2型号产品的方法");
}
}
class ProductB1 implements ProductB {
public void methodB() {
System.out.println("产品B系列中1型号产品的方法");
}
}
class ProductB2 implements ProductB {
public void methodB() {
System.out.println("产品B系列中2型号产品的方法");
}
}
以上就是咱们展现的代码案例。简单的说:无论是简单工厂,仍是工厂方法,都有一个缺陷,那就是整个模式当中只能有一个抽象产品,因此直观的,在工厂方法模式中再添加一个创造抽象产品的方法就是抽象工厂模式了,相应的固然还有添加一个抽象产品,还有一系列具体的该抽象产品的实现。