大话设计模式

本文用简洁的方法,总结常用的设计模式

设计模式主要分成三大类,每一类都有一些具体模式,总结如下

  • 创建型模式
    • 抽象工厂模式
    • 生成器模式
    • 原型模式
    • 单例模式
  • 结构型模式
    • 适配器模式
    • 桥接模式
    • 组合模式
    • 装饰模式
    • 外观模式
    • 享元模式
    • 代理模式
  • 行为模式

抽象工厂模式

 Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

抽象工厂模式主要是由父类指定一个构造方法,子类实现,而非直接调用构造方法

这个是一个不使用工厂模式的例子:

    public class Information
    {
        public string Name { get; set; }
    }
    public class CalInfo : Information
    {
        public string Description { get; set; }
    }

    public class ImageInfo : Information
    {
        public int Width { get; set; }
        public int Height { get; set; }
    }

    public class CalEngine
    {
        public void Print(CalInfo info)
        {
            Console.WriteLine("CalEngine Print" + info.ToString());
        }
    }

    public class Render
    {
        public void Print(ImageInfo info)
        {
            Console.WriteLine("Render Print" + info.ToString());
        }
    }

 

可以看到,Render和CalEngine都会使用特定的Information,Render使用ImageInfo作为参数,而CalEngine使用CalInfo作为参数

在具体使用的时候,要针对特定的情况,构造一个合适的对象传递给Print方法

        static void Main(string[] args)
        {
            var calEngine = new CalEngine();
            var render = new Render();

            // Usage1, now need print CalEngine
            calEngine.Print(new CalInfo());

            // Usage2, now need print Render
            render.Print(new ImageInfo());

        }

 

工厂模式推荐将构造实例的地方单独放在子类中实现

修改如下:

    public interface ICreator
    {
        Information Create();
    }
    public class CalEngine : IPrint, ICreator
    {
        public Information Create()
        {
            return new CalInfo();
        }

        public void Print()
        {
            Console.WriteLine("CalEngine Print" + Create().ToString());
        }
    }

    public class Render : IPrint, ICreator
    {
        public Information Create()
        {
            return new ImageInfo();
        }

        public void Print()
        {
            Console.WriteLine("Render Print" + Create().ToString());
        }
    }

 

现在调用者无需根据具体情况,构造特定类型的实例

        static void Main(string[] args)
        {
            var calEngine = new CalEngine();
            var render = new Render();

            calEngine.Print();
            render.Print();
        }

 生成器模式

Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.

生成器模式主要是当构造器初始化步骤复杂时,抽出来不同步骤的构造方法,放置在一个Builder模块中,用来屏蔽这个类本身的复杂程度

    public class Render
    {
        public Render()
        {

        }

        public void InitSize()
        {

        }

        public void InitDOM()
        {

        }

        public void InitImage()
        {

        }

        public void BindEvent()
        {

        }
    }

 

不使用该模式

        static void Main(string[] args)
        {
            // 1. Create a simple render
            var render1 = new Render();
            render1.InitDOM();

            // 2. Create a complex render
            var render2 = new Render();
            render2.InitDOM();
            render2.InitSize();
            render2.BindEvent();
        }

 

使用该模式

    public class RenderBuilder
    {
        public Render CreateSimpleRender()
        {
            var render = new Render();
            render.InitDOM();
            return render;
        }

        public Render CreateComplexRender()
        {
            var render = new Render();
            render.InitDOM();
            render.InitSize();
            render.BindEvent();
            return render;
        }
    }

 

调用

        static void Main(string[] args)
        {
            var builder = new RenderBuilder();

            // 1. Create a simple render
            var render1 = builder.CreateSimpleRender();

            // 2. Create a complex render
            var render2 = builder.CreateComplexRender();
        }

 

原型模式

Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.

很简单,就是定义克隆方法,使得其他人可以必要时复制当前对象

    public class Information
    {
        public Information() { }
        public Information(string name) { this.Name = name; }
        public string Name { get; set; }
    }

    public class Person
    {
        public int Age;
        public DateTime BirthDate;
        public string Name;
        public Information IdInfo;

        public Person ShallowClone()
        {
            return (Person)this.MemberwiseClone();
        }

        public Person DeepClone()
        {
            Person clone = (Person)this.MemberwiseClone();
            clone.IdInfo = new Information(IdInfo.Name);
            clone.Name = String.Copy(Name);
            return clone;
        }
    }

 

调用

 

        static void Main(string[] args)
        {
            var person = new Person()
            {
                Age = 12,
                BirthDate = DateTime.Now,
                Name = "aaa",
            };
            var person1 = person.DeepClone();
            var person2 = person.DeepClone();
        }

 

单例模式

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

单例模式就是指全局只能拥有一个实例

    internal class Program
    {
        static void Main(string[] args)
        {
            Singleton.GetInstance().Cal();
        }
    }

    public sealed class Singleton
    {
        private Singleton() { }

        private static Singleton _instance;

        public static Singleton GetInstance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }

        public void Cal()
        {

        }
    }

 

可以看到单例模式的实现主要是靠把构造器私有化

适配器模式

Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.

适配器模式指的是想调用一个类的方法,但是手头上的类并不兼容,准备一个适配器,用来屏蔽两个类的差异,以方便的调用方法

    public class XMLData
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public XMLData() { }
        public void Print()
        {

        }
    }

    public class JsonData
    {
        public string Title { get; set; }
        public int TotalValue { get; set; }
    }

    public class Adapter
    {
        private JsonData _data;
        public Adapter(JsonData data)
        {
            this._data = data;
        }

        public void Print()
        {
            var data = new XMLData();
            data.Name = _data.Title;
            data.Value = _data.TotalValue.ToString();
            data.Print();
        }
    }

 

桥接模式

Bridge is a structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.

桥接模式说的就是组织好类的关系,把一个庞杂的类按照不同用途拆分成多个类

    class Abstraction
    {
        protected IImplementation _implementation;

        public Abstraction(IImplementation implementation)
        {
            this._implementation = implementation;
        }

        public virtual string Operation()
        {
            return "Abstract: Base operation with:\n" +
                _implementation.OperationImplementation();
        }
    }

    class ExtendedAbstraction : Abstraction
    {
        public ExtendedAbstraction(IImplementation implementation) : base(implementation) { }

        public override string Operation()
        {
            return "ExtendedAbstraction: Extended operation with:\n" +
                base._implementation.OperationImplementation();
        }
    }


    public interface IImplementation
    {
        string OperationImplementation();
    }

    class ConcreteImplementationA : IImplementation
    {
        public string OperationImplementation()
        {
            return "ConcreteImplementationA: The result in platform A.\n";
        }
    }

    class ConcreteImplementationB : IImplementation
    {
        public string OperationImplementation()
        {
            return "ConcreteImplementationA: The result in platform B.\n";
        }
    }

    class Client
    {
        public void ClientCode(Abstraction abstraction)
        {
            Console.Write(abstraction.Operation());
        }
    }

 

先按照类型创建两个不同的类,再按照功能创建两个不同的类,再把两个类桥接在一起

        static void Main(string[] args)
        {
            Client client = new Client();

            Abstraction abstraction;

            abstraction = new Abstraction(new ConcreteImplementationA());
            client.ClientCode(abstraction);

            abstraction = new ExtendedAbstraction(new ConcreteImplementationB());
            client.ClientCode(abstraction);
        }

 组合模式

Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects.

组合模式就是借助递归来组织无限数量的对象,这些对象将会被组织成一棵树。

首先将所有对象划分成两大。

一类是简单元素,它将充当叶子节点。另一类是容器,容器能够包含叶子节点和容器。

容器自己并没有复杂逻辑,逻辑都递归的传递给了简单元素去处理,容器只是负责汇总这些结果。

装饰模式

Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.

装饰模式就是写一个包装器,扩展现有类的行为。

假如有一个基类,基类有几个派生类。当你想组合基类和派生类的方法,单纯的继承派生类做不到。

这时候可以再写一个类,继承自基类,但是内部存储一个派生类的实例引用。

外观模式

Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes.

外观模式就是定义一个类,将复杂的几个类提供的方法组合起来,对外只提供一个简单的接口,方便调用者使用

享元模式

Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.

 

代理模式

Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.

 

posted @ 2022-10-01 19:50  内心澎湃的水晶侠  阅读(570)  评论(0编辑  收藏  举报