1.装饰器模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratePattern
{
internal class Program
{
static void Main(string[] args)
{
Person p1 = new ConcretePerson("小红");
Decorate d1 = new Hat();
Decorate d2=new Tshirt();
d1.SetPerson(p1);
d2.SetPerson(d1);//核心语句 把Decorate中的person改变为d1,d1的show 为小红开始装饰:帽子
d2.Show();
Console.Read();
}
}
abstract class Person
{
public abstract void Show();
}
class ConcretePerson : Person
{
private string name;
public ConcretePerson(string name)
{
this.name = name;
}
public override void Show()
{
Console.Write($"{name}开始装饰:");
}
}
class Decorate : Person
{
Person person;
public void SetPerson(Person p)
{
this.person = p;
}
public override void Show()
{
person.Show();
}
}
class Tshirt : Decorate
{
public override void Show()
{
base.Show();
Console.Write("T恤");
}
}
class Hat : Decorate
{
public override void Show()
{
base.Show();//其实就是person的show
Console.Write("帽子");
}
}
}
2 外观模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FacadePattern
{
internal class Program
{
static void Main(string[] args)
{
Facade facade=new Facade();
facade.Open();
facade.Close();
Console.ReadLine();
}
}
class PC
{
public void Open()
{
Console.WriteLine("打开主机");
}
public void Close()
{
Console.WriteLine("关闭主机");
}
}
class Monitor
{
public void Open()
{
Console.WriteLine("打开显示器");
}
public void Close()
{
Console.WriteLine("关闭显示器");
}
}
class Facade
{
PC PC;
Monitor Monitor;
public Facade()
{
PC=new PC();
Monitor=new Monitor();
}
public void Open()
{
PC.Open();
Monitor.Open();
}
public void Close()
{
PC.Close();
Monitor.Close();
}
}
}
3.代理模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProxyPattern
{
internal class Program
{
static void Main(string[] args)
{
ProxyMath proxy=new ProxyMath();
Console.WriteLine(proxy.Add(5, 6));
Console.Read();
}
}
interface Imath
{
double Add(double x, double y);
double Subtract(double x, double y);
double Multiply(double x, double y);
double Divide(double x, double y);
}
class Math : Imath
{
public double Add(double x, double y)
{
return x+ y;
}
public double Divide(double x, double y)
{
return x /y;
}
public double Multiply(double x, double y)
{
return x*y;
}
public double Subtract(double x, double y)
{
return x - y;
}
}
class ProxyMath : Imath
{
private Math math=new Math();
public double Add(double x, double y)
{
return math.Add(x, y);
}
public double Divide(double x, double y)
{
return math.Divide(x, y);
}
public double Multiply(double x, double y)
{
return math.Multiply(x, y);
}
public double Subtract(double x, double y)
{
return math.Subtract(x, y);
}
}
}