当前位置:天才代写 > tutorial > JAVA 教程 > Java设计模式之工场要领模式

Java设计模式之工场要领模式

2017-11-11 08:00 星期六 所属: JAVA 教程 浏览:440

副标题#e#

一 、工场要领(Factory Method)模式

工场要领模式的意义是界说一个建设产物工具的工场接口,将实际建设事情推迟到子类傍边。焦点工场类不再认真产物的建设,这样焦点类成为一个抽象工场脚色,仅认真详细工场子类必需实现的接口,这样进一步抽象化的长处是使得工场要领模式可以使系统在不修改详细工场脚色的环境下引进新的产物。

二、 工场要领模式脚色与布局

抽象工场(Creator)脚色:是工场要领模式的焦点,与应用措施无关。任安在模式中建设的工具的工场类必需实现这个接口。

详细工场(Concrete Creator)脚色:这是实现抽象工场接口的详细工场类,包括与应用措施密切相关的逻辑,而且受到应用措施挪用以建设产物工具。在上图中有两个这样的脚色:BulbCreator与TubeCreator。

抽象产物(Product)脚色:工场要领模式所建设的工具的超范例,也就是产物工具的配合父类或配合拥有的接口。在上图中,这个脚色是Light。

详细产物(Concrete Product)脚色:这个脚色实现了抽象产物脚色所界说的接口。某详细产物有专门的详细工场建设,它们之间往往一一对应。

Java设计模式之工厂方式模式


#p#副标题#e#

三、一个简朴的实例

// 产物 Plant接口
public interface Plant { }
//详细产物PlantA,PlantB
public class PlantA implements Plant {
 public PlantA () {
  System.out.println("create PlantA !");
 }
 public void doSomething() {
  System.out.println(" PlantA do something ...");
 }
}
public class PlantB implements Plant {
 public PlantB () {
  System.out.println("create PlantB !");
 }
 public void doSomething() {
  System.out.println(" PlantB do something ...");
 }
}
// 产物 Fruit接口
public interface Fruit { }
//详细产物FruitA,FruitB
public class FruitA implements Fruit {
 public FruitA() {
  System.out.println("create FruitA !");
 }
 public void doSomething() {
  System.out.println(" FruitA do something ...");
 }
}
public class FruitB implements Fruit {
 public FruitB() {
  System.out.println("create FruitB !");
 }
 public void doSomething() {
  System.out.println(" FruitB do something ...");
 }
}
// 抽象工场要领
public interface AbstractFactory {
 public Plant createPlant();
 public Fruit createFruit() ;
}
//详细工场要领
public class FactoryA implements AbstractFactory {
 public Plant createPlant() {
  return new PlantA();
 }
 public Fruit createFruit() {
  return new FruitA();
 }
}
public class FactoryB implements AbstractFactory {
 public Plant createPlant() {
  return new PlantB();
 }
 public Fruit createFruit() {
  return new FruitB();
 }
}

四、工场要领模式与简朴工场模式

工场要领模式与简朴工场模式再布局上的差异不是很明明。工场要领类的焦点是一个抽象工场类,而简朴工场模式把焦点放在一个详细类上。

工场要领模式之所以有一个体名叫多态性工场模式是因为详细工场类都有配合的接口,可能有配合的抽象父类。

当系统扩展需要添加新的产物工具时,仅仅需要添加一个详细工具以及一个详细工场工具,原有工场工具不需要举办任何修改,也不需要修改客户端,很好的切合了"开放-关闭"原则。而简朴工场模式在添加新产物工具后不得不修改工场要领,扩展性欠好。

工场要领模式退化后可以演酿成简朴工场模式。

 

    关键字:

天才代写-代写联系方式