1.单例模式
using System;
using System.Threading.Tasks;
namespace 单例模式
{
//单利模式 唯一性 保证重复引用同一个实例来节约资源
//整个系统 一个类 只有一个实例对象
class Program
{
static void Main(string[] args)
{
//Singleton.CheckObject().ConsoleID();
//Singleton.CheckObject().ConsoleID();
//Singleton.CheckObject().ConsoleID();
Parallel.For(0, 3, index =>
{
var id = Singleton.CheckObject().ConsoleID();
Console.WriteLine("第{0}次打印{1}", index, id);
});
Console.ReadKey();
}
}
class Singleton
{
private Guid guid;
private Singleton()
{
guid = Guid.NewGuid();
}
public static Singleton key;
public static Object o = new Object();
public static Singleton CheckObject()
{
if (key is null)
{
lock (o)//加锁防止并发
{
if (key is null)
{
key = new Singleton();
}
}
}
return key;
}
public Guid ConsoleID()
{
return guid;
}
}
}
2.策略模式SSS
using Microsoft.Extensions.DependencyInjection;
using System;
namespace 策略模式
{
//策略模式
//定义一系列的算法类,将每个算法分别封装起来可以相互替换
//类似于依赖注入
class Program
{
static void Main(string[] args)
{
AA aa = new AA();
BB bb = new BB();
AppServer appserver = new AppServer(bb);//更方便的切换方法实现
appserver.Create(null);
Console.ReadKey();
}
}
public class AppServer
{
private readonly IDosomthing idosomthing;
public AppServer(IDosomthing dosmething)
{
idosomthing = dosmething;
}
public void Create(object obj)
{
idosomthing.CreateSomthing(obj);
}
}
public interface IDosomthing
{
void CreateSomthing(object o);
}
//具体的实现是在每个类中
public class AA : IDosomthing
{
public void CreateSomthing(object o)
{
Console.WriteLine("这是AA汽车");
}
}
public class BB : IDosomthing
{
public void CreateSomthing(object o)
{
Console.WriteLine("这是BB汽车");
}
}
//改为依赖注入
//Microsoft.Extensions.DependencyInjection引用
//static void Main(string[] args)
//{
// var services = new ServiceCollection();
// services.AddScoped<IDosomthing, BB>();
// services.AddScoped<AppServer>();
// var builder = services.BuildServiceProvider();
// AppServer appserver = builder.GetRequiredService<AppServer>();
// appserver.Create(null);
// Console.ReadKey();
//}
}
3.建造者模式
using System;
namespace 建造者模式
{
//商家进行规定 下家来实行
class Program
{
static void Main(string[] args)
{
Builder e = new Elephent();
e.Work();
}
}
public abstract class Builder
{
protected abstract void Step1();
protected abstract void Step2();
protected abstract void Step3();
public void Work()//商家固定了步骤顺序
{
Step1();
Step2();
Step3();
}
}
public class Elephent : Builder
{
protected override void Step1()
{
Console.WriteLine("第一步打开冰箱门");
}
protected override void Step2()
{
Console.WriteLine("第二步把大象放进去");
}
protected override void Step3()
{
Console.WriteLine("第三步关上冰箱门");
}
}
}
4.抽象工厂三步曲SSS
using System;
using System.Data;
//简单工厂 工厂模式 抽象工厂
//目的:隐藏创建对象的细节,根据条件创建需要的实例
namespace _04抽象工厂三步曲
{
class Program
{
static void Main(string[] args)
{
var factory = new SqlServerFactory();
var dao = factory.Create();
//抽象工厂调用
var fac = new ERP();
fac.CreateOracle();
fac.CreateSqlserver();
}
}
public interface IDAO
{
void GetConnection();
}
class SqlserverDAO : IDAO
{
public void GetConnection()
{
Console.WriteLine("Sqlserver");
}
}
class OracleDAO : IDAO
{
public void GetConnection()
{
Console.WriteLine("Oracle");
}
}
static class Factory //简单工厂 缺点:需要不停增加if判断新的
{
public static IDAO Create(string name)
{
if (name.Equals("Sqlserver"))
{
return new SqlserverDAO();
}
if(name.Equals("Oracle"))
{
return new OracleDAO();
}
else
{
return null;
}
}
}
//==================================================================
//工厂模式
abstract class AbstractionFactory
{
public abstract IDAO Create();
}
class SqlServerFactory : AbstractionFactory
{
public override IDAO Create()
{
return new SqlserverDAO();
}
}
class OracleFactory : AbstractionFactory
{
public override IDAO Create()
{
return new OracleDAO();
}
}
//======================================
//抽象工厂
abstract class AllFactory
{
public abstract IDAO CreateSqlserver();
public abstract IDAO CreateOracle();
}
class ERP : AllFactory
{
public override IDAO CreateOracle()
{
return new OracleDAO();
}
public override IDAO CreateSqlserver()
{
return new SqlserverDAO();
}
}
}
5.模板模式SSS
using System;
namespace _05模板模式
{
//制作出必要部分 其余子类自定义
class Program
{
static void Main(string[] args)
{
//ClassDo cd = new ClassDo();
//cd.GetResult();
Templete t = new ClassDo();
t.GetResult();
}
}
abstract class Templete
{
void Step1()
{
Console.WriteLine("步骤1");
}
protected abstract void Step2();//留着子类根据需求实现
protected virtual void Step3()//子类可选择是否重写
{
Console.WriteLine("步骤3");
}
public void GetResult()
{
Step1();
Step2();
Step3();
}
}
class ClassDo : Templete
{
protected override void Step2()
{
Console.WriteLine("子类实现步骤2");
}
}
}
6.外观模式
using System;
namespace _06外观模式
{
//目的 隐藏复杂的实现
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
interface IUserRepository//用户仓储
{
object GetById(int id);
}
interface IRoleRepository//角色仓储
{
IEquatable<string> GetRoles(int userId);
}
interface IAuthorityRepository//权限仓储
{
IEquatable<string> GetAuthorites(IEquatable<string> roles);
}
}
7.中介者模式
using System;
namespace _07中介者模式
{
//目的: 由中间者来负责对接双方的交互
class Program
{
static void Main(string[] args)
{
var fangdong = new People("房东");
var zuke = new People("租客");
Mediator zhongjie = new Mediator();
zhongjie.Trade(500, fangdong, zuke);
}
}
class People
{
public People(string name)
{
Name = name;
}
public string Name { get; }
public int Money { get; set; }
}
class Mediator//中介
{
public void Trade(int money, People user1, People user2)
{
user1.Money += money;
user2.Money -= money;
Console.WriteLine("{0}的钱增加了{1}", user1.Name, money);
Console.WriteLine("{0}的钱减少了{1}", user2.Name, money);
}
}
//====================================================
//领域驱动中的领域服务
class User { }
class Role { }
class UserInRole
{
public User User { get; set; }
public Role Role { get; set; }
}
class UserRoleServide
{
public void AssignRole(User user, Role role)
{
new UserInRole() { User = user, Role = role };
}
}
//class 调用
//{
// var service = new UserRoleServide();
// var user = new User();
// var role = new Role();
// service.AssignRole(user, role);
//}
}
8.适配器模式
using System;
namespace _08适配器模式
{
//原文 将一个类的接口转换成客户希望的另一个接口
//使得原本用于接口不兼容而不能一起工作的类可以一起工作
class Program
{
static void Main(string[] args)
{
IExpectedInterface client = new ExistObj();
Console.WriteLine(client.Name);
//如何在不实例化NewClass的情况下调用到Age
Adapter adapter = new Adapter();
//Adapter继承了IExpectedInterface可以隐式转换
client = adapter;
Console.WriteLine(client.Name);
//通过接口获取到了两个实现类的属性
}
}
interface IExpectedInterface
{
public string Name { get; set; }
}
class ExistObj: IExpectedInterface
{
//现有一直在使用的
public string Name { get; set; } = "张三";
}
class NewClass
{
public int Age { get; set; } = 10;
}
//需要一个适配器进行转换
//Adapter继承了IExpectedInterface便可以进行转换
class Adapter : NewClass, IExpectedInterface
{
public Adapter()
{
Name = base.Age.ToString();
}
public string Name { get; set; }
}
}
9.观察者模式SSS
using System;
using System.Collections.Generic;
namespace _09观察者模式
{
//目的:使内部的对象行动一致
class Program
{
static void Main(string[] args)
{
var teacher = new Teacher();
teacher.Add(new Action1());
teacher.Add(new Action2());
teacher.Command();
}
}
interface IAction
{
void Do();
}
class Action1 : IAction
{
public void Do()
{
Console.WriteLine("Action1");
}
}
class Action2 : IAction
{
public void Do()
{
Console.WriteLine("Action2");
}
}
class Teacher
{
List<IAction> listActions = new List<IAction>();
public void Add(IAction action)
{
listActions.Add(action);
}
public void Remove(IAction action)
{
listActions.Remove(action);
}
public void Command()
{
//listActions.ForEach(action => action.Do());
foreach (var item in listActions)
{
item.Do();
}
}
}
}
//观察设计者模式2
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat();
Mouse mouse1 = new Mouse("张三", cat);
Mouse mouse2 = new Mouse("李四", cat);
Mouse mouse3 = new Mouse("王五", cat);
cat.CatMouse();
Console.ReadKey();
}
}
public class Cat
{
public void CatMouse()
{
Console.WriteLine("猫来了");
StartRun();
}
public event Action StartRun;
}
public class Mouse
{
private string name;
public Mouse(string mName, Cat cat)
{
name = mName;
cat.StartRun += Runaway;
}
public void Runaway()
{
Console.WriteLine("老鼠" + name + "跑了");
}
}
10.享元模式
using System;
using System.Collections.Generic;
namespace _10享元模式
{
//缓存模式
class Program
{
static void Main(string[] args)
{
CacheManager cacheManager = new();
var value = cacheManager.GetOperation<Operation>("key", () => new() { Name = "haha" });
Console.WriteLine(value.Name);
//第二次从缓存中取出.
var value2 = cacheManager.GetOperation<Operation>("key");
Console.WriteLine(value2.Name);
}
}
interface IOperation
{
string Name { get; set; }
}
class Operation : IOperation
{
public string Name { get; set; }
}
class CacheManager
{
private static Dictionary<string, IOperation> options = new();
public IOperation GetOperation<T>(string key,Func<T> func=default)
where T:IOperation,new()
{
if(!options.ContainsKey(key))
{
options.Add(key, func is null ?new T():func());
}
return options[key];
}
}
}
11.桥接模式
using Microsoft.EntityFrameworkCore;
using System;
namespace _11桥接模式
{
//目的 双方独立 又能关联
//如下为Entity仓储模式示例
class Program
{
static void Main(string[] args)
{
var repository = new RespositoryBase<User>(new MyDbcontext());
repository.Add(new User { Id = 1 });
}
}
class User
{
public int Id { get; set; }
}
class MyDbcontext : DbContext
{
}
interface IRespository<TEntity> where TEntity :class
{
void Add(TEntity entity);
void Remove(TEntity entity);
}
class RespositoryBase<TEntity> : IRespository<TEntity> where TEntity : class
{
//通过基类进行桥接
private readonly DbContext context;
public RespositoryBase(DbContext context)
{
this.context = context;
}
public void Add(TEntity entity)
{
context.Add(entity);
}
public void Remove(TEntity entity)
{
context.Remove(entity);
}
}
}
12.迭代模式
using System;
using System.Collections;
using System.Collections.Generic;
namespace _12迭代器模式
{
//IEnumerator
class Program
{
static void Main(string[] args)
{
var users = new List<User>()
{
new User(){Name="张三"},
new User(){Name="张四"},
new User(){Name="张五"}
};
var collection = new UserCollection(users.ToArray());
while(collection.HasNext())
{
var user = (User)collection.Next();
Console.WriteLine(user.Name);
}
}
}
interface IIterator
{
bool HasNext();
object Next();
}
class UserCollection : IIterator
{
private readonly User[] users;
int index;
public UserCollection(User[] users)
{
this.users = users;
}
public bool HasNext()
{
return index < users.Length;
}
public object Next()
{
var instance = users[index];
index++;
return instance;
}
}
class User
{
public string Name { get; set; }
}
//===================================================
//使用IEnumerator接口
class UserCollection2 : IEnumerator
{
private readonly User[] users;
int index = -1;
public UserCollection2(User[] users)
{
this.users = users;
}
public object Current { get; private set; }
public bool MoveNext()
{
index++;
Current = users[index];
return index < users.Length - 1;
}
public void Reset()
{
index = -1;
}
}
}
13.装饰器模式
using System;
namespace _13装饰器模式
{
//目的 重用功能扩展功能
class Program
{
static void Main(string[] args)
{
new Anchor().Inner();
Console.WriteLine();
new Bold(new Anchor()).Inner();
Console.WriteLine();
new Italic(new Bold(new Anchor())).Inner();
Console.WriteLine();
}
}
abstract class HtmlElement
{
protected internal abstract void Inner();
protected abstract string TagName { get; }
}
class Anchor : HtmlElement
{
protected override string TagName => "a";
protected internal override void Inner()
{
Console.WriteLine("<{0}>Anchor</{0}>",TagName);
}
}
class Paramgraph : HtmlElement
{
protected override string TagName => "a";//a标签
protected internal override void Inner()
{
Console.WriteLine("<{0}>Paragraph</{0}>", TagName);
}
}
abstract class Decorator : HtmlElement
{
private readonly HtmlElement htmlElement;
public Decorator(HtmlElement element)
{
htmlElement = element;
}
protected internal override void Inner()
{
Console.Write($"<{TagName}>");
htmlElement.Inner();
Console.WriteLine($"</{TagName}>");
}
}
class Bold : Decorator
{
protected override string TagName => "b";//加粗
public Bold(HtmlElement element) : base(element)
{
}
}
class Italic : Decorator
{
protected override string TagName => "i";//倾斜
public Italic(HtmlElement element) : base(element)
{
}
}
}
14.代理模式
using System;
namespace _14代理模式
{
//完成没有完成的内容
//代理模式 和策略模式的差别
//代理模式需要继承于同一个接口 策略模式则不需要
class Program
{
static void Main(string[] args)
{
ProxyAction proxyAction = new ProxyAction(new RealAction());
proxyAction.Do();
}
}
interface IAction
{
void Do();
}
class RealAction : IAction
{
public void Do()
{
Console.WriteLine("我是真的");
}
}
class ProxyAction : IAction//代理
{
private readonly IAction action;
public ProxyAction(IAction action)
{
this.action = action;
}
public void Do()
{
Console.WriteLine("我是真的之前");
action.Do();
Console.WriteLine("我是真的之后");
}
}
}
15.责任链模式SSS
using System;
namespace _15责任链模式
{
class Program
{
static void Main(string[] args)
{
var context = new ProcessContext();
var leader = new ProcessA();
var manager = new ProcessB();
var boss = new ProcessC();
leader.Next = manager;
manager.Next = boss;
leader.Process(context);
}
}
class ProcessContext
{
public string Name { get; set; }
}
abstract class ProcessHandler
{
public ProcessHandler Next { get; set; }
public abstract void Process(ProcessContext context);
}
class ProcessA : ProcessHandler
{
public override void Process(ProcessContext context)
{
context.Name = "组长";
Console.WriteLine("流程A{0}处理", context.Name);
Next?.Process(context);
}
}
class ProcessB : ProcessHandler
{
public override void Process(ProcessContext context)
{
context.Name = "主管";
Console.WriteLine("流程B{0}处理", context.Name);
Next?.Process(context);
}
}
class ProcessC : ProcessHandler
{
public override void Process(ProcessContext context)
{
context.Name = "经理";
Console.WriteLine("流程C{0}处理", context.Name);
Next?.Process(context);
}
}
}
16.过滤器模式
using System;
using System.Collections.Generic;
using System.Linq;
namespace _16过滤器模式
{
class Program
{
static void Main(string[] args)
{
var list = Enumerable.Range(1, 1000);
FilterA filterA = new FilterA();
FilterB filterB = new FilterB();
list = filterA.Filter(list);
list = filterB.Filter(list);
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
interface IFilter
{
IEnumerable<int> Filter(IEnumerable<int> list);
}
class FilterA : IFilter
{
public IEnumerable<int> Filter(IEnumerable<int> list)
{
if (list.Sum() >100)
{
Console.WriteLine("超过了100");
list = list.Skip(10).ToList();//干掉前十个
}
return list;
}
}
class FilterB : IFilter
{
public IEnumerable<int> Filter(IEnumerable<int> list)
{
if (list.Sum() > 40)
{
list = list.Take(10).ToList();//超过40取前10个
}
return list;
}
}
}
17.组合模式
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace _17组合模式
{
//一棵树
class Program
{
static void Main(string[] args)
{
Node node = new Node()
{
Name = "根节点",
Children = new List<Node>()
{
//new Node()
//{
// Name = "子节点",
// Children = new List<Node>(){};
//}
new(){Name = "第一个子节点"},
new()
{
Name = "第二个子节点",
Children = new List<Node>
{
new(){Name = "第二个子节点的子节点"}
}
},
}
};
Console.WriteLine(node);
Console.ReadKey();
}
}
class Node
{
public string Name { get; set; }
public ICollection<Node> Children { get; set; } = new HashSet<Node>();
public override string ToString()
{
var builder = new StringBuilder();
builder.Append(Name);
builder.AppendLine();
loop(builder, Children, 1);
return builder.ToString();
}
void loop(StringBuilder builder,IEnumerable<Node> nodes,int deep)
{
foreach (var child in nodes)
{
builder.AppendFormat("|{0}{1}", new string('-', deep), child.Name);
builder.AppendLine();
deep++;
loop(builder, child.Children, deep);
}
}
}
}
18.备忘录模式
using System;
using System.Collections.Generic;
namespace _18备忘录模式
{
//目的 保存历史记录 随时恢复
class Program
{
static void Main(string[] args)
{
var history = new History();
var user = new User { Name = "第一次记录" };
history.Add(user.Save());
user.Name = "进行修改";
history.Add(user.Save());
user.Name = "再次进行修改";
history.Add(user.Save());
Console.WriteLine("获取再次修改{0}",history.Get(1).user.Name);
}
}
class User
{
public string Name { get; set; }
public Momento Save() => new(new() { Name = Name });
public User Restor(Momento momento) => momento.user;
}
class Momento
{
public Momento(User user)
{
this.user = user;
}
public User user { get; }
}
class History
{
List<Momento> Momentos { get; set; } = new();
public void Add(Momento momento) => Momentos.Add(momento);
public Momento Get(int version) => Momentos[version];
}
}
19.命令模式
using System;
namespace _19命令模式
{
//对类方法进行一层包装进行隐藏
class Program
{
static void Main(string[] args)
{
WashCommand washCommand = new WashCommand(new Person());
washCommand.Execute();
}
}
class Person
{
public void WashHand()
{
Console.WriteLine("洗手");
}
}
interface ICommand
{
void Execute();
}
class WashCommand : ICommand
{
private readonly Person person;
public WashCommand(Person person)
{
this.person = person;
}
public void Execute()
{
person.WashHand();
}
}
}
该笔记是学习自B站UP猪 Teacher周的视屏做的笔记