Java-马士兵设计模式学习笔记-工厂模式-抽象工厂模式
一、概述
1.抽象工厂:当情况是需要产生一系列产品,若需更换产品,则要求一系列产品一起换,且要控制一系列产品的产生过程,此时可考虑抽象工厂模式。例:小明装修屋子,把电视、冰箱都替换掉,他这次需要把电视、冰箱换成三星的,下次装修可能要换成海尔的。此时可设计抽象类Telveison及Fridge负责产生产品,抽象工厂AbstractFactory负责产生一系列产品
PS:抽象工厂与普通工厂各自的优缺点:
(1)普通工厂容易在产品维度进行扩展,但产生系列产品时不方便,且易造成工厂类泛滥
(2)抽象工厂增加新产品时,要修改AbstractFactory等多处地方
二、类结构
1.Televison.java
2.Fridge.java
3.SamsumgTelevison.java
4.SamsungFridge.java
5.HaierTevevison.java
6.HaierFridge.java
7.AbstractFactory.java
8.SamsungFactory.java
9.HaierFactory.java
三、代码
1.Televison.java
public abstract class Televison { abstract void show(); }
2.Fridge.java
public abstract class Fridge { abstract void cool(); }
3.SamsumgTelevison.java
public class SamsungTelevison extends Televison { @Override public void show(){ System.out.println("SamsungTelevison showing..........."); } }
4.SamsungFridge.java
public class SamsungFridge extends Fridge { @Override void cool() { System.out.println("SamsungFridge cooling"); } }
5.HaierTevevison.java
public class HaierTelevison extends Televison { @Override void show() { System.out.println("海尔电视 showinng..........."); } }
6.HaierFridge.java
public class HaierFridge extends Fridge { @Override void cool() { System.out.println("海尔冰箱冷却中............"); } }
7.AbstractFactory.java
public abstract class AbstractFactory { abstract Televison createTelevison(); abstract Fridge createFridge(); }
8.SamsungFactory.java
public class SamsungFactory extends AbstractFactory { @Override Televison createTelevison() { return new SamsungTelevison(); } @Override Fridge createFridge() { return new SamsungFridge(); } }
9.HaierFactory.java
public class HaierFactory extends AbstractFactory { @Override Televison createTelevison() { return new HaierTelevison(); } @Override Fridge createFridge() { return new HaierFridge(); } }
10.Test.java
public class Test { @org.junit.Test public void test(){ AbstractFactory factory = new SamsungFactory(); Televison tv = factory.createTelevison(); Fridge fridge = factory.createFridge(); tv.show(); fridge.cool(); System.out.println("======================================="); factory = new HaierFactory(); tv = factory.createTelevison(); fridge = factory.createFridge(); tv.show(); fridge.cool(); } }
运行结果:
You can do anything you set your mind to, man!