程序设计--设计模式
设计模式
设计的终极目标是“对扩展开放,对修改关闭。”,解释为:新增功能只需要增加dll、新类库,就能用(基本不能实现)。
设计模式分为3种类型:
1.创建型设计模式
2.结构型设计模式
3.行为型设计模式
一、创建型设计模式
关注对象的创建
1、单例模式
保证进程中,某个类只有一个实例。
单例模式:把对象的创建权限关闭,提供一个公开的静态方法,起到对象重用。
用到单例模式的例子:数据临时存储的地方 / 缓存 / 静态字典 / 数据库连接池 / 线程池 / IOC的容器实例
a.懒汉模式
如何做:
- 第一步,私有化构造函数
- 第二步,公开的静态方法提供对象实例(在此方法中调用构造函数,创建实例)
- 第三步,创建两个私有全局唯一静态变量(一个实例变量,一个锁)
来看一下代码实现:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DesignModel_Singleton
{
/// <summary>
/// 此单例模式为懒汉式
/// </summary>
public class Singleton
{
/// <summary>
/// 单例模式需要把构造函数私有化。
/// </summary>
private Singleton()
{
long result = 0;
for(int i = 0;i<10000;i++)
{
result++;
}
Thread.Sleep(1000);
Console.WriteLine($"{this.GetType().Name}被构造了一次,线程:{Thread.CurrentThread.ManagedThreadId}!!!");
}
//全局唯一静态 重用这个变量
private static volatile Singleton _Singleton = null;
//锁
private static object SingLetonLock = new object();
/// <summary>
/// 公开的静态方法提供实例对象
/// </summary>
/// <returns></returns>
public static Singleton CreateInstance()
{
Console.WriteLine($"当前线程:{Thread.CurrentThread.ManagedThreadId}");
if(null == _Singleton)//两层相同的判断是必要。
{
lock(SingLetonLock)
{
if(null ==_Singleton)//两层相同的判断是必要。
{
_Singleton =new Singleton();
}
}
}
return _Singleton;
}
}
}
调用实例:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DesignModel_Singleton
{
class Program
{
static void Main(string[] args)
{
try
{
#region 懒汉式单例模式
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
for (int i = 0; i < 5; i++)
{
taskList.Add(taskFactory.StartNew(() =>
{
Singleton singleton = Singleton.CreateInstance();
}));
}
Task.WaitAll(taskList.ToArray());
#endregion
}
catch (Exception e)
{
}
}
}
}
b.饿汉模式
利用静态构造函数只被调用一次特点,在静态构造函数里给静态变量实例化,实现单例模式。
代码实现:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DesignModel_Singleton
{
/// <summary>
/// 单例模式
/// 饿汉式,只要使用此类,便会实例化对象储存在_SingletonSecond变量中。
/// </summary>
public class SingletonSecond
{
/// <summary>
/// 私有构造函数
/// </summary>
private SingletonSecond()
{
long result = 0;
for (int i = 0; i < 10000; i++)
{
result++;
}
Thread.Sleep(1000);
Console.WriteLine($"私有构造函数被调用{this.GetType().Name}被构造了一次,线程:{Thread.CurrentThread.ManagedThreadId}!!!");
}
//静态变量
private static SingletonSecond _SingletonSecond = null;
/// <summary>
/// 静态构造函数,由crl保证在使用此类型前被调用,且只调用一次。
/// 在静态构造函数里调用私有构造函数实例化变量。
/// </summary>
static SingletonSecond()
{
_SingletonSecond = new SingletonSecond();
Console.WriteLine($"静态构造函数被调用,线程:{Thread.CurrentThread.ManagedThreadId}!!!");
}
public static SingletonSecond CreateInstance()
{
return _SingletonSecond;
}
}
}
调用:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DesignModel_Singleton
{
class Program
{
static void Main(string[] args)
{
try
{
#region 饿汉式单例模式
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
for (int i = 0; i < 5; i++)
{
taskList.Add(taskFactory.StartNew(() =>
{
SingletonSecond singletonSecond = SingletonSecond.CreateInstance();
}));
}
Task.WaitAll(taskList.ToArray());
#endregion
}
catch (Exception e)
{
}
}
}
}
c.饿汉模式2
代码实现:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DesignModel_Singleton
{
public class SingletonThird
{
/// <summary>
/// 单例模式
/// 饿汉式
/// </summary>
private SingletonThird()
{
long result = 0;
for (int i = 0; i < 10000; i++)
{
result++;
}
Thread.Sleep(1000);
Console.WriteLine($"私有构造函数被调用{this.GetType().Name}被构造了一次,线程:{Thread.CurrentThread.ManagedThreadId}!!!");
}
//静态字段:在第一次使用这个类之前,有CLR保证,初始或且只初始化一次
//静态字段比静态构造函数还要早调用。
private static SingletonThird _SingletonThird = new SingletonThird();
public static SingletonThird CreateInstance()
{
return _SingletonThird;
}
}
}
调用:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DesignModel_Singleton
{
class Program
{
static void Main(string[] args)
{
try
{
#region 饿汉式2单例模式
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
for (int i = 0; i < 5; i++)
{
taskList.Add(taskFactory.StartNew(() =>
{
SingletonThird singletonThird = SingletonThird.CreateInstance();
}));
}
Task.WaitAll(taskList.ToArray());
#endregion
}
catch (Exception e)
{
}
}
}
}
2、原型模式
原型模式为了解决对象重复创建的问题
原型模式是在单例模式的基础上Clone单例模式里的静态实例,所以原型模式避免了重复创建,原型模式每次创建出来的实例都是独立的。
原型模式:把对象的创建权限关闭,提供一个公开的静态方法,提供全新的对象,不走构造方法。
代码实现:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace DesignModel_Singleton
{
/// <summary>
/// 此模式为原型模式
/// 原型模式和单例模式写法很像,但有本质区别
/// </summary>
public class Prototype
{
/// <summary>
/// 私有构造函数
/// </summary>
private Prototype()
{
long result = 0;
for (int i = 0; i < 10000; i++)
{
result++;
}
Thread.Sleep(1000);
Console.WriteLine($"私有构造函数被调用{this.GetType().Name}被构造了一次,线程:{Thread.CurrentThread.ManagedThreadId}!!!");
}
//静态变量
private static Prototype _Prototype = null;
/// <summary>
/// 静态构造函数,由crl保证在使用此类型前被调用,且只调用一次。
/// 在静态构造函数里调用私有构造函数实例化变量。
/// </summary>
static Prototype()
{
_Prototype = new Prototype();
Console.WriteLine($"静态构造函数被调用,线程:{Thread.CurrentThread.ManagedThreadId}!!!");
}
/// <summary>
/// 原型模式:解决对象重复创建的问题
/// 通过MemberwiseClone来Clone新对象,避免重复创建
/// </summary>
/// <returns></returns>
public static Prototype CreateInstancePrototype()
{
Prototype prototype = (Prototype)_Prototype.MemberwiseClone();
return prototype;
}
}
}
3、三大工厂
a.简单工厂
核心思想:想去掉细节,想去掉什么东西,咱就封装一下,转移细节。
用到的类:
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel_ThreeBigFactory
{
/// <summary>
/// 种族
/// </summary>
public interface IRace
{
void ShowKing();
}
/// <summary>
/// 人类
/// </summary>
public class Human : IRace
{
public void ShowKing()
{
Console.WriteLine($"The Race is {this.GetType().Name},This King is YaSe");
}
}
/// <summary>
/// 兽族
/// </summary>
public class ORC : IRace
{
public void ShowKing()
{
Console.WriteLine($"The Race is {this.GetType().Name},This King is LuJuRen");
}
}
/// <summary>
/// 暗夜
/// </summary>
public class NE : IRace
{
public void ShowKing()
{
Console.WriteLine($"The Race is {this.GetType().Name},This King is JingLing");
}
}
/// <summary>
/// 不死族
/// </summary>
public class Undead : IRace
{
public void ShowKing()
{
Console.WriteLine($"The Race is {this.GetType().Name},This King is YeWang");
}
}
}
工厂实现:
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel_ThreeBigFactory
{
/// <summary>
/// 简单工厂
/// </summary>
public class ObjectFactory
{
/// <summary>
/// 将依赖转移到工厂里。
/// </summary>
/// <param name="raceType"></param>
/// <returns></returns>
public static IRace CreateRace(RaceType raceType)
{
IRace race = null;
switch(raceType)
{
case RaceType.Human:
race = new Human();
break;
case RaceType.NE:
race = new NE();
break;
case RaceType.ORC:
race = new ORC();
break;
case RaceType.Undead:
race = new Undead();
break;
default:
break;
}
return race;
}
}
public enum RaceType
{
Human = 1,
Undead = 2,
ORC = 3,
NE = 4,
}
}
调用:
using System;
namespace DesignModel_ThreeBigFactory
{
class Program
{
static void Main(string[] args)
{
{
Human human = new Human();//两边都是细节
}
{
IRace human = new Human();//左边是抽象,右边是细节
}
{
IRace human = ObjectFactory.CreateRace(RaceType.Human);//两边的细节都被转移了,
}
}
}
}
(1).简单工厂的用法 1
#region 简单工厂的用法 1
//在这里读取配置文件,实现改配置文件,转换程序行为。
public static string RaceTypeConfing = "读取配置文件";
/// <summary>
/// 简单工厂+配置文件,实现修改配置文件,转换程序行为。
/// </summary>
/// <returns></returns>
public static IRace CreateRaceConfig()
{
//获取配置文件中的指明要创建的类型。
RaceType raceType = (RaceType)Enum.Parse(typeof(RaceType), RaceTypeConfing);
//调用工厂创建实例
return CreateRace(raceType);
}
#endregion
(2).简单工厂的用法 2
#region 简单工厂的用法 2
//在这里读取配置文件
public static string DllName = "读取配置文件里dll的名字";
public static string DllTypeName = "读取配置文件里dll中要创建的类名";
/// <summary>
/// IOC的雏形
/// 简单工厂+反射+配置文件,实现可扩展,可配置
/// </summary>
/// <returns></returns>
public static IRace CreateRaceConfigReflection()
{
Assembly assembly = Assembly.Load(DllName);
Type type = assembly.GetType(DllTypeName);
IRace race = (IRace)Activator.CreateInstance(type);
return race;
}
#endregion
(3).简单工厂的用法 3
- 工厂可以增加一些创建逻辑:
在创建实例前后做一些事情,比如在创建实例前写一个日志。 - 工厂可以为上层屏蔽对象实例化的复杂度:
比如实例化需要多个参数,而这些参数可以由工厂提供。 - 使用工厂创建对象可扩展(尤其IOC)
- 多个类使用一个工厂也可以,一个类一个工厂也可以。
b.抽象工厂
- 抽象工厂:工厂+约束
- 抽象工厂是用来创建产品簇的,一个工厂可以创建多个对象,这多个对象是一个整体,不可分割的。
- 倾斜的可扩展性设计。
代码实现:
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel_ThreeBigFactory
{
/// <summary>
/// 抽象工厂:负责一系列产品的创建,产品之间有关联,一般看作是一个整体。
/// Army、Hero、Race、Resource创建的这四个对象,一定是有关系的。
/// </summary>
public class UndeadFactory : FactoryAbstract
{
public override IArmy CreateArmy()//IArmy为接口
{
return new UndeadArmy();// 它为实现
}
public override IHero CreateHero()
{
return new UndeadHero();
}
public override IRace CreateRace()
{
return new Undead();
}
public override IResource CreateResource()
{
return new UndeadResource();
}
}
}
工厂的抽象定义:
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel_ThreeBigFactory
{
/// <summary>
/// 工厂的抽象,规定抽象工厂要实现哪些产品
/// </summary>
public abstract class FactoryAbstract
{
public abstract IRace CreateRace();
public abstract IArmy CreateArmy();
public abstract IHero CreateHero();
public abstract IResource CreateResource();
}
}
二、结构型设计模式
关注类与类之间的关系
- 纵向关系:继承/实现 关系肯定非常紧密
- 横向关系 : 依赖、关联、组合、聚合 (关系为以此变强)
- 注意:组合优于继承
1、适配器模式
思想:适配器只是提供方法实现的桥梁,不去做具体实现。适配器里面的实现都是它调用的子类的实现或是成员对象的实现。
- 把一个类适配到原有的接口上,可以组合,可以继承。
a、对象适配器
SqlServerHelper 对象不必实现IHelper接口
using System;
using System.Collections.Generic;
using System.Text;
namespace 适配器模式
{
/// <summary>
/// 对象适配器
/// </summary>
public class Helper : IHelper
{
#region 三种方法的好处显而易见,任选其一就可以。
///方法一:属性直接new一个对象
public SqlServerHelper SqlHelper = new SqlServerHelper();
/// <summary>
/// 方法二:构造函数创建属性对象。
/// </summary>
/// <param name="sqlHelper"></param>
public Helper(SqlServerHelper sqlHelper)
{
SqlHelper = sqlHelper;
}
/// <summary>
/// 方法三:提供一个创建方法。(场景:对象实例可有可无时使用)
/// </summary>
public void CreateSqlHelper()
{
SqlHelper = new SqlServerHelper();
}
#endregion
#region 实现接口方法
public void Add()
{
SqlHelper.AddSql();
}
public void Delete()
{
SqlHelper.AddSql();
}
public void Find()
{
SqlHelper.AddSql();
}
public void Update()
{
SqlHelper.AddSql();
}
#endregion
}
}
b、类适配器
/// <summary>
/// 类适配器
/// </summary>
public class ClassHelper : SqlServerHelper, IHelper
{
public void Add()
{
base.AddSql();
}
public void Delete()
{
base.DeleteSql();
}
public void Find()
{
base.FindSql();
}
public void Update()
{
base.UpdateSql();
}
}
2、代理模式
- 通过B来完成对A的访问。
- 通过代理类来访问业务,在不修改业务类的前提下可以扩展功能。
- 例如:
增加日志功能,只需修改代理类完成,避免对业务类修改。 - 这里的代理类ProxySubject需实现业务类ProviderSubject实现的接口ISubject。因为代理类只是业务类的代理,不能改变其行为。
using System;
using System.Collections.Generic;
using System.Text;
namespace 代理模式
{
public class ProxySubject : ISubject
{
/// <summary>
/// 实现单例代理
/// </summary>
private static ISubject subject = new ProviderSubject();
/// <summary>
/// 实现缓存代理
/// </summary>
private static IDictionary<string, string> proxyDictionary = new Dictionary<string, string>();
public void DoSomething()
{
var key = "字典key";
//额外操作
if (proxyDictionary.ContainsKey(key))//如果有缓存
{
//做些什么
}
else//没有缓存则调用
{
subject.DoSomething();
}
//额外操作
}
}
}
3、装饰器模式
装饰器模式可以做到不修改业务类,动态为类型添加功能。
using System;
using System.Collections.Generic;
using System.Text;
namespace 装饰器模式
{
/// <summary>
/// 抽象类
/// </summary>
public abstract class AbstractStudent
{
public int Age { get; set; }
public string Name { get; set; }
public abstract void Study();
}
/// <summary>
/// 学生业务行为
/// </summary>
public class Student : AbstractStudent
{
public override void Study()
{
Console.WriteLine($"周1、2、3、4、5上课-----{base.Name}");
}
}
/// <summary>
/// 包一层装饰器,基础学生行为
/// </summary>
public class BaseStudentDecorator : AbstractStudent
{
public AbstractStudent Student = null;
public BaseStudentDecorator(AbstractStudent student)
{
this.Student = student;
}
public override void Study()
{
//do something
this.Student.Study();
//do something
}
}
/// <summary>
/// 在装饰器上在包一层装饰器,vip学生行为
/// </summary>
public class VIPStudentDecorator : BaseStudentDecorator
{
public AbstractStudent Student = null;
public VIPStudentDecorator(AbstractStudent student):base(student)
{
this.Student = student;
}
public override void Study()
{
Console.WriteLine($"VIP增值课程-----{this.Name}");
this.Student.Study();
//do something
}
}
}
4、外观模式
5、组合模式
6、桥接模式
7、享元模式
三、行为型设计模式
关注的是对象和行为的分离
1、模板方法
解决一个复杂业务流程中,某些步骤可能有不同的处理,需要把行为分开,模板里面通用的行为不变;子类复写完成个性化逻辑。
using System;
using System.Collections.Generic;
using System.Text;
namespace 模板模式
{
/// <summary>
/// 银行的抽象类
/// 此抽象类其实就是模板
/// </summary>
public abstract class AbstractBank
{
/// <summary>
/// 查询操作(通用行为)
/// </summary>
public bool Query(string userName, string pwd)
{
if(CheckUser(userName, pwd))
{
var balance = new Random().Next(0, 10000000);
var interest = CalculateInterest(balance);
Show(userName,balance,interest);
}
else
{
return false;
}
return true;
}
/// <summary>
/// 检查账户(通用行为)
/// </summary>
public bool CheckUser(string userName , string pwd)
{
return true;
}
/// <summary>
/// 计算利率(个性行为)
/// 抽象方法,每一种都有不同的逻辑,有需要自己实现,所以用抽象方法。
/// </summary>
public abstract double CalculateInterest(double balance);
/// <summary>
/// 展示(默认行为)
/// 默认方法,大部分方法会走这个,少数会走自己个性逻辑。所以是虚方法
/// </summary>
public virtual void Show(string name,double balance ,double interest)
{
Console.WriteLine($"尊敬的{name}客户,您的账户余额为:{balance},利息为{interest}");
}
}
/// <summary>
/// 普通银行逻辑
/// </summary>
public class BaseBank : AbstractBank
{
public override double CalculateInterest(double balance)
{
return new Random().Next(0, 1);
}
}
/// <summary>
/// 大客户银行逻辑
/// </summary>
public class BigVIPBank : AbstractBank
{
public override double CalculateInterest(double balance)
{
return new Random().Next(0, 1)+0.35;
}
public override void Show(string name, double balance, double interest)
{
Console.WriteLine($"尊敬的大客户---{name},我是本次服务人员--小娜,您账户的余额为{balance},您账户的利率为{interest}");
}
}
}
2、观察者模式
应用场景:在触发一个行为之后,会产生许多连锁反应。
using System;
using System.Collections.Generic;
using System.Text;
namespace 观察者模式
{
public class Cat
{
private List<IObserver> observerList = new List<IObserver>();
public void AddObserver(IObserver observer)
{
observerList.Add(observer);
}
public void MiaoOBserver()
{
Console.WriteLine("猫叫。。。。");
if(null != observerList)
{
foreach (var action in observerList)
{
action.Action();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace 观察者模式
{
//通用行为接口
public interface IObserver
{
void Action();
}
/// <summary>
/// mouse的行为
/// </summary>
public class Mouse : IObserver
{
public void Action()
{
this.ZhiZhi();
}
public void ZhiZhi()
{
Console.WriteLine("mouse听见Cat 叫,mouse Run");
}
}
/// <summary>
/// 小偷的行为
/// </summary>
public class Chief : IObserver
{
public void Action()
{
this.Run();
}
public void Run()
{
Console.WriteLine("chief听见Cat 叫,chief Runing");
}
}
}
3、责任链模式
场景:一个事件需要多个环节处理,并且环节顺序可调节。
步骤:
1、创建事件上下文
2、创建处理环节对象,对象为上层提供设置下一环节的方法,和业务处理方法。
3、由上层指定环节执行顺序
4、将事件传给第一个环节。
- 代码实现:
一个请假审批流程
using System;
using System.Collections.Generic;
using System.Text;
namespace 责任链模式
{
/// <summary>
/// 请假审批上下文
/// </summary>
public class EventContext
{
/// <summary>
/// 原因
/// </summary>
public string Reason { get; set; }
/// <summary>
/// 小时
/// </summary>
public int Hour { get; set; }
/// <summary>
/// 是否同意
/// </summary>
public bool IsAgree { get; set; }
}
public abstract class EemployeeAbstract
{
/// <summary>
/// 下一环节对象容器
/// </summary>
protected EemployeeAbstract _eemployee;
public string Name { get; set; }
/// <summary>
/// 审核
/// </summary>
/// <param name="hour"></param>
public abstract void Audit(EventContext context);
/// <summary>
/// 设置下一环节的对象
/// </summary>
/// <param name="eemployee"></param>
public void SetNext(EemployeeAbstract eemployee)
{
this._eemployee = eemployee;
}
}
/// <summary>
/// 主管
/// </summary>
public class Manager : EemployeeAbstract
{
public override void Audit(EventContext context)
{
if(context.Hour >= 24)
{
_eemployee.Audit(context);
}
else
{
context.IsAgree = true;
}
}
}
/// <summary>
/// 主管
/// </summary>
public class Chief : EemployeeAbstract
{
public override void Audit(EventContext context)
{
if (context.Hour >= 48)
{
_eemployee.Audit(context);
}
else
{
context.IsAgree = true;
}
}
}
/// <summary>
/// 主管
/// </summary>
public class CEO : EemployeeAbstract
{
public override void Audit(EventContext context)
{
if (context.Hour >= 128)
{
_eemployee.Audit(context);
}
else
{
context.IsAgree = true;
}
}
}
}
业务调用:
using System;
namespace 责任链模式
{
class Program
{
static void Main(string[] args)
{
var eventContext = new EventContext
{
Hour = 12,
Reason = "看病"
};
var manager = new Manager { Name = "大兵" };
var chief = new Chief { Name = "经理" };
var ceo = new CEO { Name = "亚裔CEO" };
//审批顺序由业务层指定
manager.SetNext(chief);
chief.SetNext(ceo);
manager.Audit(eventContext);
}
}
}