23种设计模式个人总结之C#版

 

目录

 

1.单例模式

2.抽象工厂模式

3.工厂方法模式

4.建造者模式

5.原型模式

6.适配器模式

7.装饰器模式

8.代理模式

9.外观模式

10.桥接模式

11.组合模式

12.享元模式

13.策略模式

14.模板方法模式

15.观察者模式

16.迭代器模式

17.责任链模式

18.命令模式

19.备忘录模式

20.状态模式

21.访问者模式

22.中介者模式

23.解释器模式


1.单例模式

untiy中单例模式有3种表达方式

第一种:(这种比较简单,但是需要新建一个空物体,并将脚本挂载上去。推荐使用此方式)

public class GameObjectPool : MonoBehaviour
{
    public static GameObjectPool _instance;
    private void Awake()
    {
        _instance = this;
    }
}

23种设计模式个人总结之C#版_第1张图片

第二种:(这种方式不用挂载脚本,不过代码量较大)

public class GameObjectPool : MonoBehaviour
{
    private GameObjectPool() { }
    private static GameObjectPool _instance;
    public static GameObjectPool GetInstance()
    {
        if (_instance == null)
        {
            //动态的生成一个名为“GameObjectPool”的对象并将单例脚本附加上去
            _instance = new GameObject("GameObjectPool").AddComponent();

        }
        return _instance;
    }
}

第三种:(这种方式需要挂载脚本,而且代码量还较大)

public class GameObjectPool : MonoBehaviour
{
    private GameObjectPool() { }
    private static GameObjectPool _instance;
    public static GameObjectPool GetInstance()
    {
        if (_instance == null)
        {
            _instance = new GameObjectPool ();

        }
        return _instance;
    }
}

第四种:(通过先Find再Get,需要将此代码挂载到名为“GameManager”的空物体上)

public class GameObjectPool : MonoBehaviour
{
    private static GameObjectPool _instance;
    public static GameObjectPool Instance
    {
        if (_instance == null)
        {
            _instance =GameObject.Find("GameManager").GetComponent();

        }
        return _instance;
    }
}

2.抽象工厂模式

23种设计模式个人总结之C#版_第2张图片


    class Client
    {
        static void Main(string[] args)
        {
            // 南昌工厂制作南昌的鸭脖和鸭架
            AbstractFactory nanChangFactory = new NanChangFactory();
            YaBo nanChangYabo = nanChangFactory.CreateYaBo();
            nanChangYabo.Print();
            YaJia nanChangYajia= nanChangFactory.CreateYaJia();
            nanChangYajia.Print();

            // 上海工厂制作上海的鸭脖和鸭架
            AbstractFactory shangHaiFactory = new ShangHaiFactory();
            shangHaiFactory.CreateYaBo().Print();
            shangHaiFactory.CreateYaJia().Print();

            Console.Read();
        }
    }

    public abstract class AbstractFactory// 抽象工厂类
    {
        public abstract YaBo CreateYaBo();
        public abstract YaJia CreateYaJia();
    }

    public class NanChangFactory : AbstractFactory// 南昌绝味工厂
    {
        
        public override YaBo CreateYaBo()// 制作南昌鸭脖
        {
            return new NanChangYaBo();
        }
        public override YaJia CreateYaJia()// 制作南昌鸭架
        {
            return new NanChangYaJia();
        }
    }

    public class ShangHaiFactory : AbstractFactory// 上海绝味工厂
    {
        public override YaBo CreateYaBo()
        {
            return new ShangHaiYaBo();
        }
        public override YaJia CreateYaJia()
        {
            return new ShangHaiYaJia();
        }
    }

    public abstract class YaBo
    {
        public abstract void Print();
    }
    public abstract class YaJia
    {
        public abstract void Print();
    }

    public class NanChangYaBo : YaBo
    {
        public override void Print()
        {
            Console.WriteLine("南昌的鸭脖");
        }
    }
    public class ShangHaiYaBo : YaBo
    {
        public override void Print()
        {
            Console.WriteLine("上海的鸭脖");
        }
    }

    public class NanChangYaJia : YaJia
    {
        public override void Print()
        {
            Console.WriteLine("南昌的鸭架子");
        }
    }
    public class ShangHaiYaJia : YaJia
    {
        public override void Print()
        {
            Console.WriteLine("上海的鸭架子");
        }
    }

3.工厂方法模式

23种设计模式个人总结之C#版_第3张图片


     public static void Main(string[] args)
        {

            LiveFactory liveFactory = new MusicFactory();
            Live musicLive = liveFactory.Create();
            musicLive.Action();
            Console.ReadLine();
          }

 public abstract class Live
    {
        public abstract void Action();
    }
    public class Music : Live
    {
        public override void Action()
        {
            Console.WriteLine("哼哼哈嘿,快使用刷结棍!");
        }
    }
    public class Bread : Live
    {
        public override void Action()
        {
            Console.WriteLine("努力,面包会有的,鸡蛋也会有的。");
        }
    }
    public abstract class LiveFactory
    {
        public abstract Live Create();
    }
    public class MusicFactory : LiveFactory
    {
        public override Live Create()
        {
            return new Music();
        }
    }
    public class BreadFactory : LiveFactory
    {
        public override Live Create()
        {
            return new Bread();
        }
    }

=》哼哼哈嘿,快使用双结棍! 

4.建造者模式

23种设计模式个人总结之C#版_第4张图片


    class Customer
    {
        static void Main(string[] args)
        {
            Director director = new Director();
            Builder b1 = new ConcreteBuilder1();
            Builder b2 = new ConcreteBuilder2();

            director.Construct(b1);// 老板叫员工去组装第一台电脑
   
            Computer computer1 = b1.GetComputer();// 组装完,组装人员搬来组装好的电脑
            computer1.Show();
           
            director.Construct(b2);// 老板叫员工去组装第二台电脑
            Computer computer2 = b2.GetComputer();
            computer2.Show();

            Console.Read();
        }
    }
    public class Director
    { 
        public void Construct(Builder builder)// 组装电脑
        {
            builder.BuildPartCPU();
            builder.BuildPartMainBoard();
        }
    }

    public class Computer// 电脑类
    {
        private IList parts = new List();
        public void Add(string part)
        {
            parts.Add(part);
        }
        public void Show()
        {
            Console.WriteLine("电脑开始在组装.......");
            foreach (string part in parts)
            {
                Console.WriteLine("组件"+part+"已装好");
            }

            Console.WriteLine("电脑组装好了");
        }
    }

    public abstract class Builder// 抽象建造者
    {
        public abstract void BuildPartCPU();// 装CPU
        public abstract void BuildPartMainBoard();// 装主板       
        public abstract Computer GetComputer();// 获得组装好的电脑
    }
    public class ConcreteBuilder1 : Builder
    {
        Computer computer = new Computer();
        public override void BuildPartCPU()
        {
            computer.Add("CPU1");
        }
        public override void BuildPartMainBoard()
        {
            computer.Add("Main board1");
        }
        public override Computer GetComputer()
        {
            return computer;
        }
    }
    public class ConcreteBuilder2 : Builder
    {
        Computer computer = new Computer();
        public override void BuildPartCPU()
        {
            computer.Add("CPU2");
        }
        public override void BuildPartMainBoard()
        {
            computer.Add("Main board2");
        }
        public override Computer GetComputer()
        {
            return computer;
        }
    }

 23种设计模式个人总结之C#版_第5张图片

5.原型模式

23种设计模式个人总结之C#版_第6张图片

class Program
    {
        static void Main(string[] args)
        {
            MonkeyPrototype prototypeMonkey=new ConcretePrototype ("Monkey");
            MonkeyPrototype clone1 = prototypeMonkey.Clone() as ConcretePrototype;
            Console.WriteLine("克隆1:" + clone1.name);
            MonkeyPrototype clone2 = prototypeMonkey.Clone() as ConcretePrototype;
            Console.WriteLine("克隆2:" + clone2.name);
            Console.ReadLine();
        }
    }
    public abstract class MonkeyPrototype //孙悟空原型
    {
        public string name { get; set; }
        public MonkeyPrototype(string Name)
        {
            name = Name;
        }
        public abstract MonkeyPrototype Clone();
    }
    public class ConcretePrototype:MonkeyPrototype
    {
        public ConcretePrototype(string id) : base(id) { }
        public override MonkeyPrototype Clone()//浅拷贝
        {
            return (MonkeyPrototype)MemberwiseClone();//调用MemberwiseClone()的是浅拷贝
        }
    }

6.适配器模式

23种设计模式个人总结之C#版_第7张图片

class Target
    {
        public virtual void Request()
        {
            Console.WriteLine("普通请求");
        }
    }
    class Adapter:Target
    {
         Adaptee adaptee = new Adaptee();
        public override void Request()
        {
            adaptee.SpecificRequest();
        }
    }
    class Adaptee
    {
        public void SpecificRequest()
        {
            Console.WriteLine("我是需要适配的类");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Target target = new Adapter();
            target.Request();
            Console.Read();
        }
    }

 =》我是需要适配的类

7.装饰器模式

23种设计模式个人总结之C#版_第8张图片

23种设计模式个人总结之C#版_第9张图片

    class Program
    {
        static void Main(string[] args)
        {
            Phone ap = new ApplePhone(); //新买了个苹果手机
            Decorator aps = new Sticker(ap); //准备贴膜组件
            aps.Print();
 
            Decorator apa = new Accessories(ap); //过了几天新增了挂件组件
            apa.Print();
 
            Sticker s = new Sticker(ap);       //准备贴膜组件
            Accessories a = new Accessories(s);//同时准备挂件
            a.Print(); 
        }
    }
    public abstract class Phone
    {
        public abstract void Print();
    }
    public class ApplePhone:Phone
    {
        public override void Print()
        {
            Console.WriteLine("我有一部苹果手机");
        }
    }
    public abstract class Decorator:Phone
    {
        private Phone p ;    //该装饰对象装饰到的Phone组件实体对象 
        public Decorator(Phone p)
        {
            this.p = p;
        }
        public override void Print()
        {
            if (this.p != null)
            {
                p.Print();
            }
        }
    }
    public class Sticker:Decorator// 贴膜
    {
        public Sticker(Phone p) : base(p) { }
        public override void Print()
        {
            base.Print();
            AddSticker();
        }
        public void AddSticker()
        {
            Console.WriteLine("现在苹果手机有贴膜了");
        }
    }
    public class Accessories:Decorator// 手机挂件,即具体装饰者
    {
        public Accessories(Phone p) : base(p) { }
        public override void Print()
        {
            base.Print();
            AddAccessories();
        }
        public void AddAccessories()
        {
            Console.WriteLine("现在苹果手机有漂亮的挂件了");
        }
    }

 23种设计模式个人总结之C#版_第10张图片

8.代理模式

23种设计模式个人总结之C#版_第11张图片


    class Client
    {
        static void Main(string[] args)
        {
            Person proxy = new Friend();
            proxy.BuyProduct();
            Console.Read();
        }
    }
    public abstract class Person
    {
        public abstract void BuyProduct();
    }
    public class RealBuyPerson : Person
    {
        public override void BuyProduct()
        {
            Console.WriteLine("帮我买一个IPhone和一台苹果电脑");
        }
    }
    public class Friend:Person
    {
        RealBuyPerson realSubject;
        public override void BuyProduct()
        {
            Console.WriteLine("通过代理类访问真实实体对象的方法");
            if (realSubject == null)
            {
                realSubject = new RealBuyPerson();
            }
            PreBuyProduct();
            realSubject.BuyProduct();
            this.PostBuyProduct();
        }
        public void PreBuyProduct()
        {
            // 可能不知一个朋友叫这位朋友带东西,首先这位出国的朋友要对每一位朋友要带的东西列一个清单等
            Console.WriteLine("我怕弄糊涂了,需要列一张清单,张三:要带相机,李四:要带Iphone...........");
        }
        public void PostBuyProduct()
        {
            Console.WriteLine("终于买完了,现在要对东西分一下,相机是张三的;Iphone是李四的..........");
        }
    }

 

9.外观模式

23种设计模式个人总结之C#版_第12张图片23种设计模式个人总结之C#版_第13张图片

    class Client
    {
        static void Main(string[] args)
        {
            Facade facade = new Facade();
            facade.MethodA();
            facade.MethodB();
            Console.Read();
        }
    }
    class SubSystemOne
    {
        public void MethodOne()
        {
            Console.WriteLine("子系统方法一");
        }
    }
    class SubSystemTwo
    {
        public void MethodTwo()
        {
            Console.WriteLine("子系统方法二");
        }
    }
    class SubSystemThree
    {
        public void MethodThree()
        {
            Console.WriteLine("子系统方法三");
        }
    }
    class SubSystemFour
    {
        public void MethodFour()
        {
            Console.WriteLine("子系统犯法四");
        }
    }
    class Facade
    {
        SubSystemOne one;
        SubSystemTwo two;
        SubSystemThree three;
        SubSystemFour four;
        public Facade()
        {
            one = new SubSystemOne();
            two = new SubSystemTwo();
            three = new SubSystemThree();
            four = new SubSystemFour();
        }
        public void MethodA()
        {
            Console.WriteLine("\n方法组合A()---");
            one.MethodOne();
            two.MethodTwo();
            four.MethodFour();
        }
        public void MethodB()
        {
            Console.WriteLine("\n方法组B()---");
            two.MethodTwo();
            three.MethodThree();
        }
    }

 23种设计模式个人总结之C#版_第14张图片

10.桥接模式

23种设计模式个人总结之C#版_第15张图片

    class Client
    {
        static void Main(string[] args)
        {
            ISoftware wechat = new WeChat();
            ISoftware qq = new QQ();

            Console.WriteLine("ios系统运行软件:");
            System ios = new IOS();
            ios.Run(wechat);
            ios.Run(qq);

            Console.WriteLine("");

            Console.WriteLine("Android系统运行软件:");
            System android = new Android();
            ios.Run(wechat);
            ios.Run(qq);

            Console.Read();
        }
    }
    public interface ISoftware
    {
        void Running();
    }
    public class WeChat:ISoftware
    {
        public void Running()
        {
            Console.WriteLine("微信已经运行");
        }
    }
    public class QQ : ISoftware
    {
        public void Running()
        {
            Console.WriteLine("QQ已经运行");
        }
    }
    public abstract class System
    {
        public abstract void Run(ISoftware software);
    }
    public class IOS:System 
    {
        public override void Run(ISoftware software)
        {
            Console.WriteLine("欢迎来到IOS系统");
            software.Running();
        }
    }
    public class Android: System 
    {
        public override void Run(ISoftware software)
        {
            Console.WriteLine("欢迎来到Android系统");
            software.Running();
        }
    }

 23种设计模式个人总结之C#版_第16张图片

11.组合模式

23种设计模式个人总结之C#版_第17张图片

    //抽象构件,它是叶子和容器共同的父类,并且声明了叶子和容器的所有方法
    abstract class AbstractFile
    {
        public abstract void Add(AbstractFile file);//新增文件
        public abstract void Delete(AbstractFile file);//删除文件
        public abstract AbstractFile GetChildFile(int i);//获取子构件(可以使文件,也可以是文件夹)
        public abstract void KillVirue();//对文件进行杀毒
    }
    class Folder:AbstractFile//文件夹
    {
        private List fileList = new List();
        private string name;
        public Folder(string name)
        {
            this.name = name;
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public override void Add(AbstractFile file)
        {
            fileList.Add(file);
        }
 
        public override void Delete(AbstractFile file)
        {
            fileList.Remove(file);
        }
 
        public override AbstractFile GetChildFile(int i)
        {
            return fileList[i] as AbstractFile;
        }
 
        public override void KillVirue()
        {
            Console.WriteLine("对文件夹{0}进行杀毒",name);
            foreach (AbstractFile obj in fileList)
            {
                obj.KillVirue();
            }
        }
    }
class ImageFile:AbstractFile//图片文件
    {
        private string name;
 
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public ImageFile(string name)
        {
            this.name = name;
        }
        public override void Add(AbstractFile file)
        {
            Console.WriteLine("对不起,不支持该方法");
        }
        public override void Delete(AbstractFile file)
        {
            Console.WriteLine("对不起,不支持该方法");
        }
        public override AbstractFile GetChildFile(int i)
        {
            Console.WriteLine("对不起,不支持该方法");
            return null;
        }
        public override void KillVirue()
        {
            //模拟杀毒
            Console.WriteLine("已经对{0}进行了杀毒", name);
        }
    }
class TextFile:AbstractFile//文本文件
    {
        private string name;
 
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public TextFile(string name)
        {
            this.name = name;
        }
        public override void Add(AbstractFile file)
        {
            Console.WriteLine("对不起,不支持该方法");
        }
        public override void Delete(AbstractFile file)
        {
            Console.WriteLine("对不起,不支持该方法");
        }
        public override AbstractFile GetChildFile(int i)
        {
            Console.WriteLine("对不起,不支持该方法");
            return null;
        }
        public override void KillVirue()
        {
            //模拟杀毒
            Console.WriteLine("已经对{0}进行了杀毒", name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            AbstractFile file1, file2, folder1,file3, folder2, folder3;
            folder1 = new Folder("我的视频");
            folder2 = new Folder("我的图片");
            folder3 = new Folder("我的资料");
 
            file1 = new TextFile("文本1");
 
            file2 = new ImageFile("图像2");
            file3 = new TextFile("文本2");
            folder1.Add(file1);
            folder2.Add(file2);
            folder2.Add(file3);
            folder2.KillVirue();
            Console.ReadLine();
        }
    }

 

12.享元模式

       我们可以共用一个 Hello world 对象,其中字符串 “Hello world” 为内部状态,可共享;字体颜色为外部状态,不可共享,由客户端设定。

23种设计模式个人总结之C#版_第18张图片

    class Program
    {
        static void Main(string[] args)
        {
            School school = new School();
            Student student = school.GetStudent(1);
            Console.WriteLine(student.ToString());
            student = school.GetStudent(2);
            Console.WriteLine(student.ToString());
            Console.ReadKey();
        }
    }
    public abstract class abStudent
    {
        public string Name;
        public string schName;
        public string Sex;
        public abStudent()
        {
            schName = "西南科技大学";
            Sex = "男";
        }

        public override string ToString()
        {
            return string.Format("我叫{0},性别{1},在读学校{2}", Name, Sex, schName);
        }
    }
    public class Student : abStudent
    {
        public Student(string name)
        {
            Name = name;
        }
    }
    public class School
    {
        private Dictionary StudentList;
        public School()
        {
            StudentList = new Dictionary();
            StudentList.Add(1, new Student("张三"));
            StudentList.Add(2, new Student("李四"));
        }
        public Student GetStudent(int num)
        {
            return StudentList[num] as Student;
        }
    }

 

13.策略模式

class Program
    {
        static void Main(string[] args)
        {
            Context PShow = new Context(new PersonStragety());
            Console.WriteLine("单人票单价为:{0}", PShow.GetTax(100.00));
            Context GShow = new Context(new Group());
            Console.WriteLine("团体票单价为:{0}", GShow.GetTax(100.00));

            Console.Read();
        }
    }
    public interface Stragety
    {
        double CalculateTax(double income);
    }   
    public class PersonStragety:Stragety//单人票
    {
        public double CalculateTax(double income)
        {
            return income;
        }
    }
    public class Group:Stragety//团体票
    {
        public double CalculateTax(double income)
        {
            return income*0.9f;
        }
    }
    public class Context
    {
        private Stragety m_stragety;
        public Context (Stragety stragety)
        {
            m_stragety = stragety;
        }
        public double GetTax(double income)
        {
            return m_stragety.CalculateTax(income);
        }
    }

 

14.模板方法模式

23种设计模式个人总结之C#版_第19张图片

 class Client
    {
        static void Main(string[] args)
        {
            Spinach spinach = new Spinach();
            spinach.CookVegetabel();
            Console.Read();
        }
    }
    public abstract class Vegetabel
    {
        // 模板方法,不要把模版方法定义为Virtual或abstract方法,避免被子类重写,防止更改流程的执行顺序
        public void CookVegetabel()
        {
            Console.WriteLine("抄蔬菜的一般做法");
            pourOil();
            HeatOil();
            pourVegetable();
            stir_fry();
        }
        public void pourOil()
        {
            Console.WriteLine("倒油");
        }
        public void HeatOil()
        {
            Console.WriteLine("把油烧热");
        }
        public abstract void pourVegetable();// 油热了之后倒蔬菜下去,具体哪种蔬菜由子类决定
        public void stir_fry()
        {
            Console.WriteLine("翻炒");
        }
    }
    public class Spinach : Vegetabel// 菠菜
    {

        public override void pourVegetable()
        {
            Console.WriteLine("倒菠菜进锅中");
        }
    }
    public class ChineseCabbage : Vegetabel// 大白菜
    {
        public override void pourVegetable()
        {
            Console.WriteLine("倒大白菜进锅中");
        }
    }

 23种设计模式个人总结之C#版_第20张图片

15.观察者模式

23种设计模式个人总结之C#版_第21张图片

public abstract class Blog// 订阅号抽象类
    {
        private List observers = new List();
        public string Symbol { get; set; }//描写订阅号的相关信息
        public string Info { get; set; }//描写此次update的信息
        public Blog(string symbol, string info)
        {
            Symbol = symbol;
            Info = info;
        }
        // 对同一个订阅号,新增和删除订阅者的操作
        public void AddObserver(IObserver ob)
        {
            observers.Add(ob);
        }
        public void RemoveObserver(IObserver ob)
        {
            observers.Remove(ob);
        }
        public void Update()
        {
            foreach (IObserver ob in observers)// 遍历订阅者列表进行通知
            {
                if (ob != null)
                {
                    ob.Receive(this);
                }
            }
        }
    }
    public class MyBlog : Blog// 具体订阅号类
    {
        public MyBlog(string symbol, string info)
            : base(symbol, info) { }
    }
    public interface IObserver// 订阅者接口
    {
        void Receive(Blog tenxun);
    }
    public class Subscriber : IObserver// 具体的订阅者类
    {
        public string Name { get; set; }
        public Subscriber(string name)
        {
            Name = name;
        }
        public void Receive(Blog xmfdsh)
        {
            Console.WriteLine("订阅者 {0} 观察到了{1}{2}", Name, xmfdsh.Symbol, xmfdsh.Info);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Blog xmfdsh = new MyBlog("xmfdsh", "发布了一篇新博客");

            xmfdsh.AddObserver(new Subscriber("张三"));
            xmfdsh.AddObserver(new Subscriber("李四"));
            xmfdsh.AddObserver(new Subscriber("王五"));
            xmfdsh.AddObserver(new Subscriber("赵六"));
 
            xmfdsh.Update();//更新信息
            Console.ReadLine();//输出结果,此时所有的订阅者都已经得到博客的新消息
        }
    }

 

16.迭代器模式

23种设计模式个人总结之C#版_第22张图片

    class Program
    {
        static void Main(string[] args)
        {
            ConcreteAggregate monkey = new ConcreteAggregate();
            monkey[0] = "猴子";
            monkey[1] = "刘木同";
            monkey[2] = "笨蛋";
            monkey[3] = "小弟";
            monkey[4] = "领导";
            monkey[5] = "内部人员";
            monkey[6] = "小偷";

            Iterator i = new ConcreteIterator(monkey);
            object item = i.First();//从第一个乘客开始
            while (!i.IsDone())
            {
                Console.WriteLine("{0}请买火车票", i.CurrentItem());//若没买票,请补票
                i.Next();//遍历下一个
            }
            Console.Read();
        }
    }
    abstract class Iterator
    {
        public abstract object First();//1开始对象
        public abstract object Next();//2得到下一个对象
        public abstract bool IsDone();//3判断是否到结尾
        public abstract object CurrentItem();//4当前对象
    }
    abstract class Aggregate//聚集抽象类
    {
        public abstract Iterator CreateIterator();//创建迭代器
    }
    class ConcreteIterator : Iterator//具体迭代器类
    {
        private ConcreteAggregate aggregate;//定义一个具体聚集对象
        private int current = 0;
        public ConcreteIterator(ConcreteAggregate aggregate)
        {
            this.aggregate = aggregate;//初始化时将具体的聚集对象传入
        }
        public override object First()//得到聚集的第一个对象
        {
            return aggregate[0];
        }
        public override object Next()//得到聚集的下一个对象
        {
            object ret = null;
            current++;
            if (current < aggregate.Count)
            {
                ret = aggregate[current];
            }
            return ret;
        }
        public override bool IsDone()//判断当前是否遍历到结尾,到结尾返回true
        {
            return current >= aggregate.Count ? true : false;
        }
        public override object CurrentItem()
        {
            return aggregate[current];//返回当前的聚集对象
        }
    }  
    class ConcreteAggregate : Aggregate//具体聚集类
    {
        private IList items = new List();
        public override Iterator CreateIterator()
        {
            return new ConcreteIterator(this);
        }
        public int Count
        {
            get { return items.Count; }
        }
        public object this[int index]
        {
            get { return items[index]; }
            set { items.Insert(index, value); }
        }
    }

 23种设计模式个人总结之C#版_第23张图片

17.责任链模式

23种设计模式个人总结之C#版_第24张图片

    public class PurchaseRequest// 采购请求
    {
        
        public double Amount { get; set; }// 金额
        public string ProductName { get; set; }
        public PurchaseRequest(double amount, string productName)
        {
            Amount = amount;
            ProductName = productName;
        }
    }
    public abstract class Approver// 审批人,Handler
    {
        public Approver NextApprover { get; set; }
        public string Name { get; set; }
        public Approver(string name)
        {
            Name = name;
        }
        public abstract void ProcessRequest(PurchaseRequest request);
    }
    public class Manager : Approver
    {
        public Manager(string name): base(name) { }
        public override void ProcessRequest(PurchaseRequest request)
        {
            if (request.Amount < 10000.0)
            {
                Console.WriteLine("{0}-{1}  想买  {2}", this, Name, request.ProductName);
            }
            else if (NextApprover != null)
            {
                NextApprover.ProcessRequest(request);
            }
        }
    }
    public class VicePresident : Approver// ConcreteHandler,副总
    {
        public VicePresident(string name): base(name) { }
        public override void ProcessRequest(PurchaseRequest request)
        {
            if (request.Amount < 25000.0)
            {
                Console.WriteLine("{0}-{1}  想买  {2}", this, Name, request.ProductName);
            }
            else if (NextApprover != null)
            {
                NextApprover.ProcessRequest(request);
            }
        }
    }
    public class President : Approver// ConcreteHandler,总经理
    {
        public President(string name): base(name) { }
        public override void ProcessRequest(PurchaseRequest request)
        {
            if (request.Amount < 100000.0)
            {
                Console.WriteLine("{0}-{1}  想买  {2}", this, Name, request.ProductName);
            }
            else
            {
                Console.WriteLine("Request需要组织一个会议讨论");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            PurchaseRequest requestTelphone = new PurchaseRequest(4000.0, "手机");
            PurchaseRequest requestSoftware = new PurchaseRequest(10000.0, "软件");
            PurchaseRequest requestComputers = new PurchaseRequest(40000.0, "电脑");

            Approver manager = new Manager("张三");
            Approver Vp = new VicePresident("李四");
            Approver Pre = new President("王五");
        
            manager.NextApprover = Vp;// 设置责任链
            Vp.NextApprover = Pre;

            manager.ProcessRequest(requestTelphone); // 处理请求
            manager.ProcessRequest(requestSoftware);
            manager.ProcessRequest(requestComputers);
            Console.ReadLine();
        }
    }

 

18.命令模式

23种设计模式个人总结之C#版_第25张图片

 class Program
    {
        static void Main(string[] args)
        {
            OrderReceiver o = new OrderReceiver(); //命令的响应者      >响应传达者传达的命令
            Command ecmd = new examcmd(o);       //命令的传达和监视者>传达发出这的命令给响应者
            Invoke ka = new Invoke(ecmd);        //命令的发出者      
            ka.Init();                           //>传达给传递者扩散命令

            Console.WriteLine("考试结束后");
            Command pcmd = new papercmd(o); //命令的传达和监视者
            Invoke kb = new Invoke(pcmd);   //命令的发出者
            kb.Init();

            Console.ReadLine();
        }
    }
    public class OrderReceiver// 命令最后的执行者
    {
        public void GetExam()
        {
            Console.WriteLine("进行期中考试!");
        }
        public void GetPaper()
        {
            Console.WriteLine("交卷!");
        }
    }
    public abstract class Command// 传递命令者的抽象类
    {
        protected OrderReceiver recediver;// 命令执行者
        public Command(OrderReceiver recediver)
        {
            this.recediver = recediver;
        }
        public abstract void Action();// 执行命令的方法
    }
    public class examcmd : Command// 执行考试命令传递者
    {
        public examcmd(OrderReceiver recetive) : base(recetive) { }
        public override void Action()
        {
            recediver.GetExam();
        }
    }
    public class papercmd : Command// 执行交卷命令传递者
    {
        public papercmd(OrderReceiver request) : base(request) { }
        public override void Action()// 执行命令
        {
            
            recediver.GetPaper();//开始考试
        }
    }
    public class Invoke// 命令的发出者
    {
        protected Command cmd;
        public Invoke(Command cmd)
        {
            this.cmd = cmd;
        }
        public void Init()
        {
            cmd.Action();
        }
    }

 

19.备忘录模式

23种设计模式个人总结之C#版_第26张图片

class Program
{
    static void Main(string[] args)
    {
        var persons = new List
        {
                new ContactPerson { Name= "Learning Hard", MobileNum = "123445"},
                new ContactPerson { Name = "Tony", MobileNum = "234565"},
                new ContactPerson { Name = "Jock", MobileNum = "231455"}
            };
        var mobileOwner = new MobileOwner(persons);
        mobileOwner.Show();

        // 创建备忘录并保存备忘录对象
        var caretaker = new Caretaker { ContactM = mobileOwner.CreateMemento() };

        Console.WriteLine("----移除最后一个联系人--------");// 更改发起人联系人列表
        mobileOwner.ContactPersons.RemoveAt(2);
        mobileOwner.Show();

        Console.WriteLine("-------恢复联系人列表------");// 恢复到原始状态
        mobileOwner.RestoreMemento(caretaker.ContactM);
        mobileOwner.Show();

        Console.Read();
    }
}
public class ContactPerson
{
    public string Name { get; set; }
    public string MobileNum { get; set; }
}
public class MobileOwner// 发起人
{
    public List ContactPersons { get; set; }// 发起人需要保存的内部状态
    public MobileOwner(List persons)
    {
        ContactPersons = persons;
    }
    public ContactMemento CreateMemento()// 创建备忘录,将当期要保存的联系人列表导入到备忘录中
    {
        // 这里也应该传递深拷贝,new List方式传递的是浅拷贝,
        // 因为ContactPerson类中都是string类型,所以这里new list方式对ContactPerson对象执行了深拷贝
        // 如果ContactPerson包括非string的引用类型就会有问题,所以这里也应该用序列化传递深拷贝
        return new ContactMemento(new List(this.ContactPersons));
    }
    public void RestoreMemento(ContactMemento memento)// 将备忘录中的数据备份导入到联系人列表中
    {
       //应该传递contactPersonBack的深拷贝,深拷贝可以使用序列化来完成
        ContactPersons = memento.ContactPersonBack;
    }
    public void Show()
    {
        Console.WriteLine("联系人列表中有{0}个人,他们是:", ContactPersons.Count);
        foreach (ContactPerson p in ContactPersons)
        {
            Console.WriteLine("姓名: {0} 号码为: {1}", p.Name, p.MobileNum);
        }
    }
}
public class ContactMemento// 备忘录
{
    public List ContactPersonBack; // 保存发起人的内部状态
    public ContactMemento(List persons)
    {
        ContactPersonBack = persons;
    }
}
public class Caretaker// 管理角色
{
    public ContactMemento ContactM { get; set; }
}

 23种设计模式个人总结之C#版_第27张图片

20.状态模式

        核心思想就是:当对象的状态改变时,同时改变其行为,很好理解!就拿QQ来说,有几种状态,在线、隐身、忙碌等,每个状态对应不同的操作,而且你的好友也能看到你的状态,所以,状态模式就两点:1、可以通过改变状态来获得不同的行为。2、你的好友能同时看到你的变化。

 class Program
    {
        static void Main(string[] args)
        {
            State s = new State();
            s.Say();
            s.Say();
            s.Say();
            Console.Read();
        }
       
    }
    public interface People
    {
        void Say(State s);
    }
    public class Chinese : People
    {
        public void Say(State s)
        {
            Console.Write("现在是中文...");
            s.people = new English();
            Console.WriteLine("现在切换到了英文");
        }
    }
    public class English : People
    {
        public void Say(State s)
        {
            Console.Write("现在是英文...");
            s.people = new Chinese();
            Console.WriteLine("现在切换到了中文");
        }
    }
    public class State
    {
        public People people { get; set; }
        public State()
        {
            people = new Chinese();
            Console.WriteLine("现在默认状态是中文");
        }
        public void Say()
        {
            people.Say(this);
        }
    }

 

21.访问者模式

23种设计模式个人总结之C#版_第28张图片

    public abstract class Element
    {
        public abstract void Accept(IVistor vistor);
        public abstract void Print();
    }

    public class ElementA : Element
    {
        public override void Accept(IVistor vistor)
        {
            vistor.Visit(this);
        }
        public override void Print()
        {
            Console.WriteLine("我是元素A");
        }
    }
    public class ElementB : Element
    {
        public override void Accept(IVistor vistor)
        {
            vistor.Visit(this);
        }
        public override void Print()
        {
            Console.WriteLine("我是元素B");
        }
    }
    public interface IVistor// 抽象访问者
    {
        void Visit(ElementA a);
        void Visit(ElementB b);
    }
    public class ConcreteVistor : IVistor// 具体访问者
    {
        public void Visit(ElementA a)
        {
            a.Print();
        }
        public void Visit(ElementB b)
        {
            b.Print();
        }
    }
    public class ObjectStructure// 对象结构
    {
        private ArrayList elements = new ArrayList();
        public ArrayList Elements
        {
            get { return elements; }
        }
        public ObjectStructure()
        {
            Random ran = new Random();
            for (int i = 0; i < 6; i++)
            {
                int ranNum = ran.Next(10);
                if (ranNum > 5)
                {
                    elements.Add(new ElementA());
                }
                else
                {
                    elements.Add(new ElementB());
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ObjectStructure objectStructure = new ObjectStructure();
            foreach (Element e in objectStructure.Elements)
            {
                e.Accept(new ConcreteVistor());// 每个元素接受访问者访问
            }
            Console.Read();
        }
    }

 

 

22.中介者模式

    public abstract class AbstractCardPartner// 抽象牌友类
    {
        public int MoneyCount { get; set; }
        protected AbstractCardPartner()
        {
            MoneyCount = 0;
        }
        public abstract void ChangeCount(int count, AbstractMediator mediator);
    }
    public class ParterA : AbstractCardPartner// 牌友A类
    {
        public override void ChangeCount(int count, AbstractMediator mediator)// 依赖与抽象中介者对象
        {
            mediator.AWin(count);
        }
    }
    
    public class ParterB : AbstractCardPartner// 牌友B类
    {
        public override void ChangeCount(int count, AbstractMediator mediator)// 依赖与抽象中介者对象
        {
            mediator.BWin(count);
        }
    }
    public abstract class AbstractMediator// 抽象中介者类
    {
        protected AbstractCardPartner A;
        protected AbstractCardPartner B;
        protected AbstractMediator(AbstractCardPartner a, AbstractCardPartner b)
        {
            A = a;
            B = b;
        }
        public abstract void AWin(int count);
        public abstract void BWin(int count);
    }
    public class MediatorPater : AbstractMediator// 具体中介者类
    {
        public MediatorPater(AbstractCardPartner a, AbstractCardPartner b): base(a, b) { }
        public override void AWin(int count)
        {
            A.MoneyCount += count;
            B.MoneyCount -= count;
        }
        public override void BWin(int count)
        {
            B.MoneyCount += count;
            A.MoneyCount -= count;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            AbstractCardPartner A = new ParterA();
            AbstractCardPartner B = new ParterB(); 
            
            A.MoneyCount = 20;// 初始钱
            B.MoneyCount = 20;

            AbstractMediator mediator = new MediatorPater(A, B);
  
            A.ChangeCount(5, mediator);// A赢了
            Console.WriteLine("A 现在的钱是:{0}", A.MoneyCount);// 应该是25
            Console.WriteLine("B 现在的钱是:{0}", B.MoneyCount); // 应该是15

            B.ChangeCount(10, mediator);// B 赢了
            Console.WriteLine("A 现在的钱是:{0}", A.MoneyCount);// 应该是15
            Console.WriteLine("B 现在的钱是:{0}", B.MoneyCount); // 应该是25
            Console.Read();
        }
    }

23.解释器模式

23种设计模式个人总结之C#版_第29张图片

    class Program
    {
        static void Main(string[] args)
        {
            BooleanExp booleanExp1 = new BooleanExp("true");
            BooleanExp booleanExp2 = new BooleanExp("false");

            OrExp orExp = new OrExp(booleanExp1, booleanExp2);//或表达式
            Console.WriteLine(orExp.Interpret());

            AndExp andExp = new AndExp(booleanExp1, booleanExp2);//与表达式
            Console.WriteLine(andExp.Interpret());

            Console.Read();
        }
    }
    abstract class ExpressionClass
    {
        public abstract bool Interpret();
    }
    class BooleanExp : ExpressionClass//布尔表达式
    {
        string Context;
        public BooleanExp(string context)
        {
            Context = context;
        }
        public override bool Interpret()
        {
            return Context.ToLower() == "true";
        }
    }
    class OrExp : ExpressionClass//或表达式
    {
        BooleanExp Exp1;
        BooleanExp Exp2;

        public OrExp(BooleanExp exp1, BooleanExp exp2)
        {
            Exp1 = exp1;
            Exp2 = exp2;
        }
        public override bool Interpret()
        {
            return Exp1.Interpret() || Exp2.Interpret();
        }
    }
    class AndExp : ExpressionClass// 与表达式
    {
        BooleanExp Exp1;
        BooleanExp Exp2;
        public AndExp(BooleanExp exp1, BooleanExp exp2)
        {
            Exp1 = exp1;
            Exp2 = exp2;
        }
        public override bool Interpret()
        {
            return Exp1.Interpret() && Exp2.Interpret();
        }
    }

 

你可能感兴趣的:(23种设计模式个人总结之C#版)