常用设计模式实例代码汇总

目录

单例模式

原型模式

外观模式

简单工厂模式

工厂方法模式

抽象工厂方法

策略模式

装饰模式

观察者模式

适配器模式

状态模式(状态类切换)

状态模式(环境类切换)


单例模式

cs 复制代码
void Main()
{
	Singleton instance1 = Singleton.GetInstance();
	Singleton instance2 = Singleton.GetInstance();
	
	Console.WriteLine(instance1.GetHashCode());
	Console.WriteLine(instance2.GetHashCode());
}

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

原型模式

cs 复制代码
void Main()
{
	Resume resume1 = new Resume("桃子","20","温州");
	
	Resume resume2 = resume1.Clone();
	resume2.Name = "桃子的爸爸";
	resume2.Age = "28";

	Resume resume3 = resume1.Clone();
	resume3.Name = "桃子的妈妈";
	resume3.Age = "30";

	resume1.Display();
	resume2.Display();
	resume3.Display();

}

class Resume
{
	public string Name { get; set;}
	public string Age {get;set;}
	public string Home {get;set;}
	
	public Resume(string name, string age, string home){
		Name = name;
		Age = age;
		Home = home;
	}

	public void Display()
	{
		Console.WriteLine($"名字:{Name}");
		Console.WriteLine($"年龄:{Age}");
		Console.WriteLine($"家:{Home}");
		Console.WriteLine($"-------------------------------------");
	}
	
	public Resume Clone(){
		return new Resume(Name, Age, Home);
	}
}

外观模式

cs 复制代码
void Main()
{
	Facade facade = new Facade();
	facade.Method();
}

class SystemA
{
	public void MethodA()
	{
		Console.WriteLine("系统A开启了");
	}
}

class SystemB
{
	public void MethodB()
	{
		Console.WriteLine("系统B开启了");
	}
}

class SystemC
{
	public void MethodC()
	{
		Console.WriteLine("系统C开启了");
	}
}

class Facade
{
	private SystemA _systemA = new SystemA();
	private SystemB _systemB = new SystemB();
	private SystemC _systemC = new SystemC();

	public void Method()
	{
		_systemA.MethodA();
		_systemB.MethodB();
		_systemC.MethodC();
	}
}

简单工厂模式

cs 复制代码
void Main()
{
	Product productA = Factory.GetProduct("A");
	productA.MethodSame();
	productA.MethodDiff();

	Product productB = Factory.GetProduct("B");
	productB.MethodSame();
	productB.MethodDiff();
	
}

abstract class Product
{
	public void MethodSame()
	{
		Console.WriteLine("这里是公共的方法");
	}
	public abstract void MethodDiff();
}

class ProductA : Product
{
	public override void MethodDiff()
	{
		Console.WriteLine("这里是ProductA");
	}
}

class ProductB : Product
{
	public override void MethodDiff()
	{
		Console.WriteLine("这里是ProductB");
	}
}

class Factory
{
	public static Product GetProduct(string arg)
	{
		Product product = null;
		if (arg.Equals("A"))
		{
			product = new ProductA();
		}
		else if (arg.Equals("B"))
		{
			product = new ProductA();
		}
		return product;
	}
}

工厂方法模式

cs 复制代码
void Main()
{
	IFactory factoryA = new FactoryA();
	Product productA = factoryA.CreateProduct();
	productA.MethodSame();
	productA.MethodDo();
	
	IFactory factoryB = new FactoryB();
	Product productB = factoryB.CreateProduct();
	productB.MethodSame();
	productB.MethodDo();
}

abstract class Product{
	public void MethodSame(){
		Console.WriteLine("这是公共方法");
	}
	public abstract void MethodDo();
}

class ProductA : Product
{
	public override void MethodDo()
	{
		Console.WriteLine("这里是产品A");
	}
}

class ProductB : Product
{
	public override void MethodDo()
	{
		Console.WriteLine("这里是产品B");
	}
}

interface IFactory
{
	Product CreateProduct();
}

class FactoryA : IFactory
{
	public Product CreateProduct()
	{
		return new ProductA();
	}
}

class FactoryB : IFactory
{
	public Product CreateProduct()
	{
		return new ProductB();
	}
}

抽象工厂方法

cs 复制代码
void Main()
{
	IFactory factory1 = new Factory1();
	AbProductA productA1 = factory1.CreateProductA();
	AbProductB productB1 = factory1.CreateProductB();
	productA1.Method();
	productB1.Method();

	IFactory factory2 = new Factory2();
	AbProductA productA2 = factory2.CreateProductA();
	AbProductB productB2 = factory2.CreateProductB();
	productA2.Method();
	productB2.Method();
}

abstract class AbProductA{
	public abstract void Method();
}

abstract class AbProductB{
	public abstract void Method();
}

class ProductA1 : AbProductA
{
	public override void Method()
	{
		Console.WriteLine("这里是产品A1");
	}
}

class ProductA2 : AbProductA
{
	public override void Method()
	{
		Console.WriteLine("这里是产品A2");
	}
}

class ProductB1 : AbProductB
{
	public override void Method()
	{
		Console.WriteLine("这里是产品B1");
	}
}

class ProductB2 : AbProductB
{
	public override void Method()
	{
		Console.WriteLine("这里是产品B2");
	}
}

interface IFactory
{
	public AbProductA CreateProductA();
	public AbProductB CreateProductB();
}

class Factory1 : IFactory
{
	public AbProductA CreateProductA()
	{
		return new ProductA1();
	}

	public AbProductB CreateProductB()
	{
		return new ProductB1();
	}
}

class Factory2 : IFactory
{
	public AbProductA CreateProductA()
	{
		return new ProductA2();
	}

	public AbProductB CreateProductB()
	{
		return new ProductB2();
	}
}

策略模式

cs 复制代码
void Main()
{
	IStrategy strategyA = new StrategyA();
	Context contextA = new Context(strategyA);
	contextA.oper();

	IStrategy strategyB = new StrategyB();
	Context contextB = new Context(strategyB);
	contextB.oper();
}

interface IStrategy
{
	void Do();
}

class StrategyA : IStrategy{
	public void Do(){
		Console.WriteLine("这里是StrategyA");
	}
}

class StrategyB : IStrategy
{
	public void Do()
	{
		Console.WriteLine("这里是StrategyB");
	}
}

class Context{
	IStrategy _strategy;
	public Context(IStrategy strategy){
		_strategy = strategy;
	}
	
	public void oper(){
		_strategy.Do();
	}
}

装饰模式

cs 复制代码
void Main()
{
	Component component = new ConcreteComponent();
	Decorator decorator = new ConcreteDecorator(component);
	decorator.Operation();
}

abstract class Component {
	public abstract void Operation();
}

class ConcreteComponent : Component{
	public override void Operation(){
		Console.WriteLine("Operation");
	}
}

class Decorator : Component{
	private Component component;
	public Decorator(Component component){
		this.component = component;
	}
	public override void Operation(){
		component.Operation();
	}
}

class ConcreteDecorator : Decorator{
	public ConcreteDecorator(Component component) : base(component){
		
	}
	public override void Operation(){
		base.Operation();
		AddedBehavior();
	}
	public void AddedBehavior(){
		Console.WriteLine("AddedBehavior");
	}
}

观察者模式

cs 复制代码
void Main()
{
	Subject subject = new ConcreteSubject();
	Observer observer = new ConcreteObserver();
	subject.Attach(observer);
	subject.Notify();
}

abstract class Subject{
	protected List<Observer> observers = new List<Observer>();
	public abstract void Attach(Observer observer);
	public abstract void Detach(Observer observer);
	public abstract void Notify();
}

class ConcreteSubject : Subject
{
	public override void Attach(Observer observer)
	{
		observers.Add(observer);
	}

	public override void Detach(Observer observer)
	{
		observers.Remove(observer);
	}

	public override void Notify()
	{
		foreach (object obs in observers)
		{
			((Observer)obs).Update();
		}
	}
}

abstract class Observer{
	public abstract void Update();
}

class ConcreteObserver : Observer{
	public override void Update(){
		Console.WriteLine("调用了Update");
	}
}

适配器模式

cs 复制代码
void Main()
{
	Adaptee adaptee = new Adaptee();
	Target targetA = new Adapter(adaptee);
	targetA.Request();
}

class Target {
	public virtual void Request(){
		Console.WriteLine("目标类请求方法");
	}
}

class Adaptee {
	public void SpecificRequest(){
		Console.WriteLine("适配类的请求方法");
	}
}

class Adapter : Target {
	private Adaptee _adaptee;
	public Adapter(Adaptee adaptee){
		this._adaptee = adaptee;
	}
	public override void Request(){
		_adaptee.SpecificRequest();
	}
}

状态模式(状态类切换)

cs 复制代码
void Main()
{
	Context context = new Context(new ConcreteStateA());
	context.Condition = 1;
	context.Request();
	context.Condition = 2;
	context.Request();
}

abstract class State
{
	public abstract void Handle(Context context);
}

class ConcreteStateA : State
{
	public override void Handle(Context context)
	{
		if(context.Condition == 2){
			context.State = new ConcreteStateB();
			context.Request();
		} else {
			Console.WriteLine("Handle() in A");
		}
	}
}

class ConcreteStateB : State
{
	public override void Handle(Context context)
	{
		if (context.Condition == 1)
		{
			context.State = new ConcreteStateA();
			context.Request();
		}
		else
		{
			Console.WriteLine("Handle() in B");
		}
	}
}

class Context
{
	public State State { get; set; }
	public int Condition { get; set; }
	public Context(State state)
	{
		State = state;
	}

	public void Request()
	{
		State.Handle(this);
	}
}

状态模式(环境类切换)

cs 复制代码
void Main()
{
	Context context = new Context(new ConcreteStateA());
	context.Condition = 1;
	context.Request();
	context.Condition = 2;
	context.Request();
}

abstract class State{
	public abstract void Handle();
}

class ConcreteStateA : State
{
	public override void Handle()
	{
		Console.WriteLine("Handle() in A");
	}
}

class ConcreteStateB : State
{
	public override void Handle()
	{
		Console.WriteLine("Handle() in B");
	}
}

class Context
{
	public State State { get; set; }
	public int Condition {get;set;}
	public Context(State state){
		State = state;
	}
	
	public void Request(){
		ChangeState();
		State.Handle();
	}
	public void ChangeState(){
		if(Condition == 1){
			State = new ConcreteStateA();
		} else if(Condition == 2){
			State = new ConcreteStateB();
		}
	}
}
相关推荐
向宇it18 分钟前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
向宇it2 小时前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎
思忖小下3 小时前
梳理你的思路(从OOP到架构设计)_简介设计模式
设计模式·架构·eit
liyinuo20176 小时前
嵌入式(单片机方向)面试题总结
嵌入式硬件·设计模式·面试·设计规范
坐井观老天6 小时前
在C#中使用资源保存图像和文本和其他数据并在运行时加载
开发语言·c#
aaasssdddd968 小时前
C++的封装(十四):《设计模式》这本书
数据结构·c++·设计模式
T1an-18 小时前
设计模式之【观察者模式】
观察者模式·设计模式
pchmi9 小时前
C# OpenCV机器视觉:模板匹配
opencv·c#·机器视觉
思忖小下10 小时前
梳理你的思路(从OOP到架构设计)_设计模式Factory Method模式
设计模式·工厂方法模式·eit
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭10 小时前
C#都可以找哪些工作?
开发语言·c#