之前介紹工廠模式對一個相同屬性的物件做處理,但是當我有很多物件需要組合?這時候可以使用抽象工廠模式
抽象工廠模式定義
為一組相互關係的物件提供一個介面,來組裝起來
抽象工廠模式用法
以 Abstract Factory 設計模式的 UML 結構圖來看,根據《物件導向設計模式》(Design Patterns) 書中所述,其中定義了參與抽象工廠模式的幾個角色:
- 抽象工廠角色(AbstractFactory) : 介面宣告出可生成各抽象成品物件的操作
- 具體工廠角色(ConcreteFactory) : 具體實作出可建構具象成品物件的操作
- 抽象產品角色(AbstractProduct) : 宣告某成品物件類型之介面
- 具體產品角色(ConcreteProduct):是 ConcreteFactory 所建構的成品物件
- 用戶端: 使會使用到AbstractFactory和AbstractProduct
抽象工廠模式實例
/** * name: IProductFactory * role : AbstractFactory * description: 產品抽象類別 * Created by bryant on 2017/1/11. */ public abstract class IProductFactory { //產生播放器 public abstract IPlayer createPlayer(); //產生耳機 public abstract IEarphone createEarphone(); }
/** * name: IPlayer * role : AbstractProduct * description: 播放器抽象類別 * Created by bryant on 2017/1/11. */ abstract class IPlayer { //播放抽象 abstract public void play() ; }
/** * name: MP3Player * role : ConcreteProduct * description:MP3 播放器 * Created by bryant on 2017/1/11. */ public class MP3Player extends IPlayer { @Override public void play() { System.out.print("MP3 Player"); } }
/** * name: CDPlayer * role : ConcreteProduct * description:CD 播放器 * Created by bryant on 2017/1/11. */ public class CDPlayer extends IPlayer { @Override public void play() { System.out.print("CD Player"); } }/** * name: IEarphone * role : AbstractProduct * description: 耳機抽象類別 * Created by bryant on 2017/1/11. */ public abstract class IEarphone { public abstract void capability(); }/** * name: BeatEarphone * role : ConcreteProduct * description: BeatEarphone * Created by bryant on 2017/1/11. */ public class BeatEarphone extends IEarphone{ @Override public void capability() { System.out.println("beat耳機"); } }/** * name: StereoEarphone * role : ConcreteProduct * description: StereoEarphone * Created by bryant on 2017/1/11. */ public class StereoEarphone extends IEarphone{ @Override public void capability() { System.out.println("立體聲耳機"); } }/** * name: Walkman * role : ConcreteFactory * description: 具體工廠角色->產品功能CD、Stereo * Created by bryant on 2017/1/11. */ public class Walkman extends IProductFactory { @Override public IPlayer createPlayer() { return new CDPlayer(); } @Override public IEarphone createEarphone() { return new StereoEarphone(); } }/** * name: Phone * role : ConcreteFactory * description: 具體工廠角色->手機功能MP3、beat耳機 * Created by bryant on 2017/1/11. */ public class Phone extends IProductFactory { @Override public IPlayer createPlayer() { return new MP3Player(); } @Override public IEarphone createEarphone() { return new BeatEarphone(); } }
留言
張貼留言