11.DoFactory.GangOfFour.Flyweight.Structural
Flyweight:运用共享技术有效的支持大量细粒度的对象。
享元模式:FLYWEIGHT在拳击比赛中指最轻量级。享元模式以共享的方式高效的支持大量的细粒度对象。享元模式能做到共享的关键是区分内蕴状态和外蕴状态。内蕴状态存储在享元内部,不会随环境的改变而有所不同。外蕴状态是随环境的改变而改变的。外蕴状态不能影响内蕴状态,它们是相互独立的。将可以共享的状态和不可以共享的状态从常规类中区分开来,将不可以共享的状态从类里剔除出去。客户端不可以直接创建被共享的对象,而应当使用一个工厂对象负责创建被共享的对象。享元模式大幅度的降低内存中对象的数量。
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Flyweight.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Flyweight Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Arbitrary extrinsic state
int extrinsicstate = 22;
FlyweightFactory factory = new FlyweightFactory();
// Work with different flyweight instances
Flyweight fx = factory.GetFlyweight("X");
fx.Operation(--extrinsicstate);
Flyweight fy = factory.GetFlyweight("Y");
fy.Operation(--extrinsicstate);
Flyweight fz = factory.GetFlyweight("Z");
fz.Operation(--extrinsicstate);
UnsharedConcreteFlyweight fu = new
UnsharedConcreteFlyweight();
fu.Operation(--extrinsicstate);
// Wait for user
Console.Read();
}
}
// "FlyweightFactory"
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
// Constructor
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]);
}
}
// "Flyweight"
abstract class Flyweight
{
public abstract void Operation(int extrinsicstate);
}
// "ConcreteFlyweight"
class ConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("ConcreteFlyweight: " + extrinsicstate);
}
}
// "UnsharedConcreteFlyweight"
class UnsharedConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("UnsharedConcreteFlyweight: " +
extrinsicstate);
}
}
}
12.DoFactory.GangOfFour.Interpreter.Structural
Interpreter:给定一个语言,定义它的文法的一种表示,并定义一个解释器用于解释特定文法。
解释器模式:给定一个语言后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子。解释器模式将描述怎样在有了一个简单的文法后,使用模式设计解释这些语句。在解释器模式里面提到的语言是指任何解释器对象能够解释的任何组合。在解释器模式中需要定义一个代表文法的命令类的等级结构,也就是一系列的组合规则。每一个命令对象都有一个解释方法,代表对命令对象的解释。命令对象的等级结构中的对象的任何排列组合都是一个语言。
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Interpreter.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Interpreter Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
Context context = new Context();
// Usually a tree
ArrayList list = new ArrayList();
// Populate 'abstract syntax tree'
list.Add(new TerminalExpression());
list.Add(new NonterminalExpression());
list.Add(new TerminalExpression());
list.Add(new TerminalExpression());
// Interpret
foreach (AbstractExpression exp in list)
{
exp.Interpret(context);
}
// Wait for user
Console.Read();
}
}
// "Context"
class Context
{
}
// "AbstractExpression"
abstract class AbstractExpression
{
public abstract void Interpret(Context context);
}
// "TerminalExpression"
class TerminalExpression : AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("Called Terminal.Interpret()");
}
}
// "NonterminalExpression"
class NonterminalExpression : AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("Called Nonterminal.Interpret()");
}
}
}
13.DoFactory.GangOfFour.Iterator.Structural
Iterator:提供一种方法顺序访问一个聚合对象中的各种元素,而无需暴露该对象的内部表示。
迭代子模式:迭代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起形成的总体称之为聚集,聚集对象是能够包容一组对象的容器对象。迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。迭代子模式简化了聚集的界面。每一个聚集对象都可以有一个或一个以上的迭代子对象,每一个迭代子的迭代状态可以是彼此独立的。迭代算法可以独立于聚集角色变化。
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Iterator.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Iterator Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
ConcreteAggregate a = new ConcreteAggregate();
a[0] = "Item A";
a[1] = "Item B";
a[2] = "Item C";
a[3] = "Item D";
// Create Iterator and provide aggregate
ConcreteIterator i = new ConcreteIterator(a);
Console.WriteLine("Iterating over collection:");
object item = i.First();
while (item != null)
{
Console.WriteLine(item);
item = i.Next();
}
// Wait for user
Console.Read();
}
}
// "Aggregate"
abstract class Aggregate
{
public abstract Iterator CreateIterator();
}
// "ConcreteAggregate"
class ConcreteAggregate : Aggregate
{
private ArrayList items = new ArrayList();
public override Iterator CreateIterator()
{
return new ConcreteIterator(this);
}
// Property
public int Count
{
get{ return items.Count; }
}
// Indexer
public object this[int index]
{
get{ return items[index]; }
set{ items.Insert(index, value); }
}
}
// "Iterator"
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
// "ConcreteIterator"
class ConcreteIterator : Iterator
{
private ConcreteAggregate aggregate;
private int current = 0;
// Constructor
public ConcreteIterator(ConcreteAggregate aggregate)
{
this.aggregate = aggregate;
}
public override object First()
{
return aggregate[0];
}
public override object Next()
{
object ret = null;
if (current < aggregate.Count - 1)
{
ret = aggregate[++current];
}
return ret;
}
public override object CurrentItem()
{
return aggregate[current];
}
public override bool IsDone()
{
return current >= aggregate.Count ? true : false ;
}
}
}
14.DoFactory.GangOfFour.Mediator.Structural
Mediator:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式相互引用,从而使得耦合松散,可以独立改变相互之间的交互。
调停者模式:调停者模式包装了一系列对象相互作用的方式,使得这些对象不必相互明显作用。从而使他们可以松散偶合。当某些对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用。保证这些作用可以彼此独立的变化。调停者模式将多对多的相互作用转化为一对多的相互作用。调停者模式将对象的行为和协作抽象化,把对象在小尺度的行为上与其他对象的相互作用分开处理。
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Mediator.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Mediator Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
ConcreteMediator m = new ConcreteMediator();
ConcreteColleague1 c1 = new ConcreteColleague1(m);
ConcreteColleague2 c2 = new ConcreteColleague2(m);
m.Colleague1 = c1;
m.Colleague2 = c2;
c1.Send("How are you?");
c2.Send("Fine, thanks");
// Wait for user
Console.Read();
}
}
// "Mediator"
abstract class Mediator
{
public abstract void Send(string message,
Colleague colleague);
}
// "ConcreteMediator"
class ConcreteMediator : Mediator
{
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public ConcreteColleague1 Colleague1
{
set{ colleague1 = value; }
}
public ConcreteColleague2 Colleague2
{
set{ colleague2 = value; }
}
public override void Send(string message,
Colleague colleague)
{
if (colleague == colleague1)
{
colleague2.Notify(message);
}
else
{
colleague1.Notify(message);
}
}
}
// "Colleague"
abstract class Colleague
{
protected Mediator mediator;
// Constructor
public Colleague(Mediator mediator)
{
this.mediator = mediator;
}
}
// "ConcreteColleague1"
class ConcreteColleague1 : Colleague
{
// Constructor
public ConcreteColleague1(Mediator mediator)
: base(mediator)
{
}
public void Send(string message)
{
mediator.Send(message, this);
}
public void Notify(string message)
{
Console.WriteLine("Colleague1 gets message: "
+ message);
}
}
// "ConcreteColleague2"
class ConcreteColleague2 : Colleague
{
// Constructor
public ConcreteColleague2(Mediator mediator)
: base(mediator)
{
}
public void Send(string message)
{
mediator.Send(message, this);
}
public void Notify(string message)
{
Console.WriteLine("Colleague2 gets message: "
+ message);
}
}
}
15.DoFactory.GangOfFour.Memento.Structural
Memento:不破坏封装的前提下,捕获对象的内部状态,并在该对象之外保存这个状态。
备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捉住,并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。
using System;
namespace DoFactory.GangOfFour.Memento.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Memento Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
Originator o = new Originator();
o.State = "On";
// Store internal state
Caretaker c = new Caretaker();
c.Memento = o.CreateMemento();
// Continue changing originator
o.State = "Off";
// Restore saved state
o.SetMemento(c.Memento);
// Wait for user
Console.Read();
}
}
// "Originator"
class Originator
{
private string state;
// Property
public string State
{
get{ return state; }
set
{
state = value;
Console.WriteLine("State = " + state);
}
}
public Memento CreateMemento()
{
return (new Memento(state));
}
public void SetMemento(Memento memento)
{
Console.WriteLine("Restoring state");
State = memento.State;
}
}
// "Memento"
class Memento
{
private string state;
// Constructor
public Memento(string state)
{
this.state = state;
}
// Property
public string State
{
get{ return state; }
}
}
// "Caretaker"
class Caretaker
{
private Memento memento;
// Property
public Memento Memento
{
set{ memento = value; }
get{ return memento; }
}
}
}
16.DoFactory.GangOfFour.Observer.Structural
Observer:定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生变化时依赖于它的所有的对象都得到通知和刷新。
观察者模式:观察者模式定义了一种一队多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Observer.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Observer Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Configure Observer pattern
ConcreteSubject s = new ConcreteSubject();
s.Attach(new ConcreteObserver(s,"X"));
s.Attach(new ConcreteObserver(s,"Y"));
s.Attach(new ConcreteObserver(s,"Z"));
// Change subject and notify observers
s.SubjectState = "ABC";
s.Notify();
// Wait for user
Console.Read();
}
}
// "Subject"
abstract class Subject
{
private ArrayList observers = new ArrayList();
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();
}
}
}
// "ConcreteSubject"
class ConcreteSubject : Subject
{
private string subjectState;
// Property
public string SubjectState
{
get{ return subjectState; }
set{ subjectState = value; }
}
}
// "Observer"
abstract class Observer
{
public abstract void Update();
}
// "ConcreteObserver"
class ConcreteObserver : Observer
{
private string name;
private string observerState;
private ConcreteSubject subject;
// Constructor
public ConcreteObserver(
ConcreteSubject subject, string name)
{
this.subject = subject;
this.name = name;
}
public override void Update()
{
observerState = subject.SubjectState;
Console.WriteLine("Observer {0}'s new state is {1}",
name, observerState);
}
// Property
public ConcreteSubject Subject
{
get { return subject; }
set { subject = value; }
}
}
}
17.DoFactory.GangOfFour.Prototype.Structural
Prototype:用原型实例指定创建对象的种类,并且通过拷贝这个原型来创建新的对象。
原始模型模式:通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象。原始模型模式允许动态的增加或减少产品类,产品类不需要非得有任何事先确定的等级结构,原始模型模式适用于任何的等级结构。缺点是每一个类都必须配备一个克隆方法。
using System;
namespace DoFactory.GangOfFour.Prototype.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Prototype Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Create two instances and clone each
ConcretePrototype1 p1 = new ConcretePrototype1("I");
ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
Console.WriteLine ("Cloned: {0}", c1.Id);
ConcretePrototype2 p2 = new ConcretePrototype2("II");
ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
Console.WriteLine ("Cloned: {0}", c2.Id);
// Wait for user
Console.Read();
}
}
// "Prototype"
abstract class Prototype
{
private string id;
// Constructor
public Prototype(string id)
{
this.id = id;
}
// Property
public string Id
{
get{ return id; }
}
public abstract Prototype Clone();
}
// "ConcretePrototype1"
class ConcretePrototype1 : Prototype
{
// Constructor
public ConcretePrototype1(string id) : base(id)
{
}
public override Prototype Clone()
{
// Shallow copy
return (Prototype)this.MemberwiseClone();
}
}
// "ConcretePrototype2"
class ConcretePrototype2 : Prototype
{
// Constructor
public ConcretePrototype2(string id) : base(id)
{
}
public override Prototype Clone()
{
// Shallow copy
return (Prototype)this.MemberwiseClone();
}
}
}
18.DoFactory.GangOfFour.Proxy.Structural
Proxy:为其他对象提供一个代理以控制对这个对象的访问。
代理模式:代理模式给某一个对象提供一个代理对象,并由代理对象控制对源对象的引用。代理就是一个人或一个机构代表另一个人或者一个机构采取行动。某些情况下,客户不想或者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客户端分辨不出代理主题对象与真实主题对象。代理模式可以并不知道真正的被代理对象,而仅仅持有一个被代理对象的接口,这时候代理对象不能够创建被代理对象,被代理对象必须有系统的其他角色代为创建并传入。
using System;
namespace DoFactory.GangOfFour.Proxy.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Proxy Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Create proxy and request a service
Proxy proxy = new Proxy();
proxy.Request();
// Wait for user
Console.Read();
}
}
// "Subject"
abstract class Subject
{
public abstract void Request();
}
// "RealSubject"
class RealSubject : Subject
{
public override void Request()
{
Console.WriteLine("Called RealSubject.Request()");
}
}
// "Proxy"
class Proxy : Subject
{
RealSubject realSubject;
public override void Request()
{
// Use 'lazy initialization'
if (realSubject == null)
{
realSubject = new RealSubject();
}
realSubject.Request();
}
}
}
19.DoFactory.GangOfFour.Singleton.Structural
Singleton:保证一个类仅有一个实例,并提供一个访问它的全局点。
单例模式:单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例单例模式。单例模式只应在有真正的“单一实例”的需求时才可使用。
using System;
namespace DoFactory.GangOfFour.Singleton.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Singleton Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class Singleton
{
private static Singleton instance;
// Note: Constructor is 'protected'
protected Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
20.DoFactory.GangOfFour.State.Structural
State:允许一个对象再内部状态改变的时候改变它的行为。对象看起来似乎修改了所属的类。
状态模式:状态模式允许一个对象在其内部状态改变的时候改变行为。这个对象看上去象是改变了它的类一样。状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能取得的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。
using System;
namespace DoFactory.GangOfFour.State.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// State Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Setup context in a state
Context c = new Context(new ConcreteStateA());
// Issue requests, which toggles state
c.Request();
c.Request();
c.Request();
c.Request();
// Wait for user
Console.Read();
}
}
// "State"
abstract class State
{
public abstract void Handle(Context context);
}
// "ConcreteStateA"
class ConcreteStateA : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateB();
}
}
// "ConcreteStateB"
class ConcreteStateB : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateA();
}
}
// "Context"
class Context
{
private State state;
// Constructor
public Context(State state)
{
this.State = state;
}
// Property
public State State
{
get{ return state; }
set
{
state = value;
Console.WriteLine("State: " +
state.GetType().Name);
}
}
public void Request()
{
state.Handle(this);
}
}
}
设计原则及分类介绍:
http://www.cnblogs.com/furenjun/archive/2010/03/01/designPatterns.html