抽象工厂模块在开发中的应用
生活随笔
收集整理的這篇文章主要介紹了
抽象工厂模块在开发中的应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
抽象工廠是設計模塊中創建型模式的一種,它比起工廠方法模式來說,更加具有一般性,在本模式中會引入一個產品族的概念,就是說,在本模式中抽象產品會有多個,然后用抽象工廠去調用它們,具體怎么去調用由具體工廠來實現。
看下列代碼,主要實現動態生成按鈕和彈出窗口的功能,彈出窗口可以根據瀏覽器的類型去調用適合
自己的方法,按鈕也可以根據傳入的樣式和類型去自動生成按鈕。
class Program { static void Main(string[] args) { RunEnvironment run=new RunEnvironment (new RedFactory()); Console.WriteLine(run.Button.ToHtml(ButtonType.Button,"name1")); } } #region WindowOpen的抽象產品和具體產品 public abstract class WindowOpen { protected WindowOpen(string title) { Title = title; } protected string Title { get; set; } public abstract string ToHtml(string url); } public class IeWindowOpen : WindowOpen { public IeWindowOpen() : base("IE") { ? } public override string ToHtml(string url) { return string.Format("<script>Window.open('','{0}','')", url); } } public class FireFoxWindowOpen : WindowOpen { public FireFoxWindowOpen() : base("火狐") { ? } public override string ToHtml(string url) { return string.Format("<script>Window.open('','{0}','')", url); ? } } #endregion ? #region Button的抽象產品和具體產品 /// <summary> /// 按鈕類型 /// </summary> public enum ButtonType { Submit, Button, Reset, } public abstract class Button { protected Button(string className) { ClassName = className; } protected string ClassName { get; set; } public abstract string ToHtml(ButtonType buttonType, string id); } public class RedButton : Button { public RedButton() : base("Redbtn") { ? } public override string ToHtml(ButtonType buttonType, string id) { return string.Format("<input id='{2}' name='{2}' type='{0}' class='{1}' />", Enum.GetName(typeof(ButtonType), buttonType), ClassName, id); } } ? public class GreenButton : Button { public GreenButton() : base("GreenBtn") { ? } public override string ToHtml(ButtonType buttonType, string id) {return string.Format("<input id='{2}' name='{2}' type='{0}' class='{1}' />",
Enum.GetName(typeof(ButtonType), buttonType), ClassName, id);
} } #endregion ? #region 抽象工廠和具體工廠 public abstract class Factory { public abstract WindowOpen CreateWindowOpen(); public abstract Button CreateButton(); } public class GreenFactory : Factory { public override Button CreateButton() { return new GreenButton(); } public override WindowOpen CreateWindowOpen() { return new IeWindowOpen(); } } ? public class RedFactory : Factory { public override Button CreateButton() { return new RedButton(); } public override WindowOpen CreateWindowOpen() { return new IeWindowOpen(); } } ? #endregion ? #region 應用環境 public class RunEnvironment { public WindowOpen WindowOpen { get; set; } public Button Button { get; set; } public RunEnvironment(Factory factory) { this.WindowOpen = factory.CreateWindowOpen(); this.Button = factory.CreateButton(); } } #endregion看到上面代碼后,如果我們想為按鈕加一個黃色的樣式,我要示從Button類派生一個子類,去實現
黃色樣式功能就可以了,而不需要修改已有的代碼,這也很好的符合的“開閉原則(OCP)”
轉載于:https://www.cnblogs.com/lori/archive/2011/08/23/2150335.html
總結
以上是生活随笔為你收集整理的抽象工厂模块在开发中的应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件观念革命:交互设计精髓_交互设计基础
- 下一篇: 计算 KL距离 (相对熵)