posted at 2023.5.20 13:34 by 风信子
Decorator结构:动态地给一个对象添加一些额外的职责。就扩展功能而言,该模式比生成子类方式更为灵活。
abstract class Component{ public abstract void Operation(); } class ConcreteComponent : Component { public override void Operation(){ Console.WriteLine("具体对象的操作"); } } abstract class Decorator : Component{ protected Component component; public void SetComponent(Component component) { this.component = component; } public override void Operation(){ if (component != null) { component.Operation(); } } } class ConcreteDecoratorA : Decorator{ private string addedState; public override void Operation(){ base.Operation(); addedState = "New State"; Console.WriteLine("具体装饰对象A的操作"); } } class ConcreteDecoratorB : Decorator{ public override void Operation(){ base.Operation(); AddedBehavior(); Console.WriteLine("具体装饰对象B的操作"); } private void AddedBehavior(){ } } class Program{ static void Main(string[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); Console.Read(); } }
Façade结构:为子系统中的一组接口提供一个一致的界面,该模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
class Facade { SubSystemOne one; SubSystemTwo two; SubSystemThree three; SubSystemFour four; public Facade(){ one = new SubSystemOne(); two = new SubSystemTwo(); three = new SubSystemThree(); four = new SubSystemFour(); } public void MethodA(){ Console.WriteLine("\n方法组A() ---- "); one.MethodOne(); two.MethodTwo(); four.MethodFour(); } public void MethodB(){ Console.WriteLine("\n方法组B() ---- "); two.MethodTwo(); three.MethodThree(); } } class SubSystemOne{ public void MethodOne(){ Console.WriteLine(" 子系统方法一"); } } Factory Method创建:定义一个用于创建对象的接口,让子类决定将哪一个类实例化。它使一个类的实例化延迟到其子类。Factory Mehtod模式解决"单个对象"的需求变化,AbstractFactory模式解决"系列对象"的需求变化。
abstract class AbstractFactory{ public abstract AbstractProductA CreateProduct();}abstract class AbstractProduct{ }
Flyweight结构:运用共享技术有效了支持大量细粒度的对象。Flyweight是一个类的可共享实例,可以有几个。
class FlyweightFactory{ private Hashtable flyweights = new Hashtable(); public FlyweightFactory(){ flyweights.Add("X", new ConcreteFlyweight()); flyweights.Add("Y", new ConcreteFlyweight()); flyweights.Add("Z", new ConcreteFlyweight()); } public Flyweight GetFlyweight(string key) { return ((Flyweight)flyweights[key]); } } abstract class Flyweight{ public abstract void Operation(int extrinsicstate); } class ConcreteFlyweight : Flyweight{ public override void Operation(int extrinsicstate) { Console.WriteLine("具体Flyweight:" + extrinsicstate); } } class UnsharedConcreteFlyweight : Flyweight{ public override void Operation(int extrinsicstate) { Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate); } } class Program{ static void Main(string[] args) { int extrinsicstate = 22; FlyweightFactory f = new FlyweightFactory(); Flyweight fx = f.GetFlyweight("X"); fx.Operation(--extrinsicstate); Flyweight fy = f.GetFlyweight("Y"); fy.Operation(--extrinsicstate); Flyweight fz = f.GetFlyweight("Z"); fz.Operation(--extrinsicstate); UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight(); uf.Operation(--extrinsicstate); Console.Read(); } }
Interpreter行为:给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
class Context{ private string input; public string Input{ get { return input; } set { input = value; } } private string output; public string Output{ get { return output; } set { output = value; } } } abstract class AbstractExpression{ public abstract void Interpret(Context context); } class TerminalExpression : AbstractExpression{ public override void Interpret(Context context) { Console.WriteLine("终端解释器"); } } class NonterminalExpression : AbstractExpression{ public override void Interpret(Context context) { Console.WriteLine("非终端解释器"); } } class Program{ static void Main(string[] args) { Context context = new Context(); IList<AbstractExpression> list = new List<AbstractExpression>(); list.Add(new TerminalExpression()); list.Add(new NonterminalExpression()); list.Add(new TerminalExpression()); list.Add(new TerminalExpression()); foreach (AbstractExpression exp in list) { exp.Interpret(context); } Console.Read(); } }
Iterator行为:提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示。.NET框架已经封装。
static void Main(string[] args) { IList<string> a = new List<string>(); a.Add("大鸟"); a.Add("小菜"); foreach (string item in a) { Console.WriteLine("{0} 请买车票!", item); } // IEnumerator<string> e = a.GetEnumerator(); // while (e.MoveNext()){ // Console.WriteLine("{0} 请买车票!", e.Current); // } Console.Read(); }
Mediator行为:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
//联合国机构 abstract class UnitedNations{ public abstract void Declare(string message, Country colleague); } //联合国安全理事会 class UnitedNationsSecurityCouncil : UnitedNations{ private USA colleague1; private Iraq colleague2; public USA Colleague1{ set { colleague1 = value; } } public Iraq Colleague2{ set { colleague2 = value; } } public override void Declare(string message, Country colleague) { if (colleague == colleague1) { colleague2.GetMessage(message); } else{ colleague1.GetMessage(message); } } } //国家 abstract class Country{ protected UnitedNations mediator; public Country(UnitedNations mediator) { this.mediator = mediator; } } //美国 class USA : Country{ public USA(UnitedNations mediator) : base(mediator) { } //声明 public void Declare(string message) { mediator.Declare(message, this); } //获得消息 public void GetMessage(string message) { Console.WriteLine("美国获得对方信息:" + message); } } //伊拉克 class Iraq : Country{ public Iraq(UnitedNations mediator) : base(mediator) { } //声明 public void Declare(string message) { mediator.Declare(message, this); } //获得消息 public void GetMessage(string message) { Console.WriteLine("伊拉克获得对方信息:" + message); } } class Program{ static void Main(string[] args) { UnitedNationsSecurityCouncil UNSC = new UnitedNationsSecurityCouncil(); USA c1 = new USA(UNSC); Iraq c2 = new Iraq(UNSC); UNSC.Colleague1 = c1; UNSC.Colleague2 = c2; c1.Declare("不准研制核武器,否则要发动战争!"); c2.Declare("我们没有核武器,也不怕侵略。"); Console.Read(); } }
Memento行为:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到保存的状态。
class Originator{ private string state; public string State{ get { return state; } set { state = value; } } public Memento CreateMemento(){ return (new Memento(state)); } public void SetMemento(Memento memento) { state = memento.State; } public void Show(){ Console.WriteLine("State=" + state); } } class Memento{ private string state; public Memento(string state) { this.state = state; } public string State{ get { return state; } } } class Caretaker{ private Memento memento; public Memento Memento{ get { return memento; } set { memento = value; } } } class Program{ static void Main(string[] args) { Originator o = new Originator(); o.State = "On"; o.Show(); Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); o.State = "Off"; o.Show(); o.SetMemento(c.Memento); o.Show(); Console.Read(); } }
Observer行为:定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。分成推模式和拉模式。
推模式:
abstract class Subject{ private IList<Observer> observers = new List<Observer>(); //增加观察者 public void Attach(Observer observer) { observers.Add(observer); } //移除观察者 public void Detach(Observer observer) { observers.Remove(observer); } //通知 public void Notify(){ foreach (Observer o in observers) { o.Update(); } } } //具体通知者 class ConcreteSubject : Subject{ private string subjectState; //具体通知者状态 public string SubjectState { get { return subjectState; } set { subjectState = value; } } } abstract class Observer{ public abstract void Update(); } class ConcreteObserver : Observer{ private string name; private string observerState; private ConcreteSubject subject; public ConcreteObserver( ConcreteSubject subject, string name) { this.subject = subject; this.name = name; } //更新 public override void Update(){ observerState = subject.SubjectState; Console.WriteLine("观察者{0}的新状态是{1}", name, observerState); } public ConcreteSubject Subject{ get { return subject; } set { subject = value; } } } class Program { static void Main(string[] args) { ConcreteSubject s = new ConcreteSubject(); s.Attach(new ConcreteObserver(s, "X")); s.Attach(new ConcreteObserver(s, "Y")); s.Attach(new ConcreteObserver(s, "Z")); s.SubjectState = "ABC"; s.Notify(); Console.Read(); }} 拉模式:
//通知者接口 interface Subject{ void Notify(); string SubjectState{ get; set; } } //事件处理程序的委托 delegate void EventHandler(); class Secretary : Subject{ //声明一事件Update,类型为委托EventHandler public event EventHandler Update; private string action; public void Notify(){ Update(); } public string SubjectState{ get { return action; } set { action = value; } } } class Boss : Subject{ //声明一事件Update,类型为委托EventHandler public event EventHandler Update; private string action; public void Notify(){ Update(); } public string SubjectState{ get { return action; } set { action = value; } } } //看股票的同事 class StockObserver{ private string name; private Subject sub; public StockObserver(string name, Subject sub) { this.name = name; this.sub = sub; } //关闭股票行情 public void CloseStockMarket(){ Console.WriteLine("{0} {1} 关闭股票行情,继续工作!", sub.SubjectState, name); } } //看NBA的同事 class NBAObserver{ private string name; private Subject sub; public NBAObserver(string name, Subject sub) { this.name = name; this.sub = sub; } //关闭NBA直播 public void CloseNBADirectSeeding(){ Console.WriteLine("{0} {1} 关闭NBA直播,继续工作!", sub.SubjectState, name); } }class Program{ static void Main(string[] args) { //老板胡汉三 Boss huhansan = new Boss(); //看股票的同事 StockObserver tongshi1 = new StockObserver("魏关姹", huhansan); //看NBA的同事 NBAObserver tongshi2 = new NBAObserver("易管查", huhansan); huhansan.Update += new EventHandler(tongshi1.CloseStockMarket); huhansan.Update += new EventHandler(tongshi2.CloseNBADirectSeeding); //老板回来 huhansan.SubjectState = "我胡汉三回来了!"; //发出通知 huhansan.Notify(); Console.Read(); } }
c0e28e25-bde5-4f98-891c-b5ec5ef27ded|0|.0|96d5b379-7e1d-4dac-a6ba-1e50db561b04
Tags: 车, 程序, 方法, 接口, 类, 模
IT技术