清空-青空-晴空

首页‎ > ‎技术‎ > ‎

Design Pattern

模式分类
从目的来看:创建型,结构型(处理类与对象间的组合),行为型(类与对象交互中的职责分配)
从范围来看:类模式(类与子类的静态关系),对象模式(对象间的动态关系)
GoF         sourcemaking

MVP

发布者:Bowen Gu,发布时间:‎‎2009-5-29 上午3:47‎

MVP

Design Pattern Higher Level Diagram

发布者:Bowen Gu,发布时间:‎‎2009-4-15 上午6:45‎‎   [ 更新时间:‎‎2009-4-15 上午6:52‎‎ ]



李建忠--C#面向对象设计模式纵横谈Summary

发布者:Bowen Gu,发布时间:‎‎2009-4-15 上午5:27‎‎   [ 更新时间:‎‎2009-4-15 上午6:32‎‎ ]

李建忠--C#面向对象设计模式纵横谈系列 学习笔记
创建型模式
  • Singleton模式解决的是实体对象个数的问题,而其他创建型模式解决的问题都是NEW所带来的耦合问题
  • Factory MethodAbstract FactoryBuilder都需要一个额外的工厂类来负责实例化“易变对象”,而Prototype则是通过原型(一个特殊的工厂类)来克隆易变对象
  • 如果遇到“易变类”,起初的设计通常从Factory Method开始,当遇到更多的复杂变化时,在考虑重构为其他三种工厂模式

结构型模式

  • Adapter模式注重转换接口,将不吻合的接口适配对接
  • Bridge模式注重分离接口与其实现,支持多维度变化
  • Composite模式注重统一接口,将“一对多”的关系转化为“一对一”的关系
  • Decorator模式注重稳定接口,在此前提下为对象扩展功能
  • Facade模式注重简化接口,简化组件系统与外部客户程序的依赖关系
  • Flyweight模式注重保留接口,在内部使用共享技术对对象存储进行优化
  • Proxy模式注重假借接口,增加简介层来实现灵活控制
行为型模式
  • Template Method模式封装算法结构,支持算法子步骤变化
  • Strategy模式注重封装算法,支持算法的变化
  • State模式注重封装与状态相关的行为,支持状态的变化
  • Memoto模式注重封装对象状态变化,支持状态保存和恢复
  • Mediator模式注重封装对象间的交互,支持对象交互的变化
  • Chain of Responsibility模式注重封装对象责任,支持责任的变化
  • Command模式注重将请求封装为对象,支持请求的变化
  • Iterator模式注重封装集合对象内部结构,支持集合的变化
  • Interpreter模式注重封装特定领域变化,支持领域问题的频繁变化
  • Observer模式注重封装对象通知,支持通信对象的变化
  • Visitor模式注重封装对象操作变化,支持在运行是为类层次结构动态添加新的操作



23 Vistor 访问者 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-15 上午1:52‎

Definition:Represent an operation to be performed on the elements without changing the classes of the elements on which it operates. 表示一个作用于某对象结构中的各元素的操作。它可以在不改变各

类层次结构中可能经常由于引入新的行为
预料到有更改,不知道有怎么样的更改

                                                                Visitor
                                                ConcreteVisitor1     ConcreteV2
                                                 (添加新的方法--类)
                  ObjectStructure            Element
                                           ConcreteElementA CEB

class Shape{
    public abstract void Draw();
   
    public abstract void MoveTo(Point p);//新追加的
}
class Rectangle : Shape{
    public override void Draw(){
        
    }
}

class Circle : Shape{
    public override void Draw(){
        
    }
}

class Line : Shape{
    public override void Draw(){
        
    }
}

of an object structure. Visitor lets you define a new operation

元素的类的前提下定义作用于这些元素的新的操作


abstract class Shape{
    public abstract void Draw();    
//预料到有更改,不知道有怎么样的更改
    public abstract void Accept(ShapeVisitor v);
}
public abstract class ShapeVisitor{
    public abstract void Visit(Rectangle  shape);
    public abstract void Visit(Circle shape);
    public abstract void Visit(Line shape);
}

class Rectangle : Shape{
    public override void Draw(){  }
    public override void Accept(ShapeVisitor v){
        v.Visit(this);//把操作转发
    
}
}
class Circle : Shape{
    public override void Draw(){     }
    public override void Accept(ShapeVisitor v){
        v.Visit(this);//把操作转发
    
}
}
class Line : Shape{
    public override void Draw(){}
    public override void Accept(ShapeVisitor v){
        v.Visit(this);//把操作转发
    
}
}


///增加新的操作
public class MyShapeVisitor : ShapeVisitor{
    public override void Visit(Rectangle  shape){
        //增加对Rectangle的操作
    }
    public override void Visit(Circle shape){
    }
    public override void Visit(Line shape){
    }
}

class App{
    ShapeVisitor sv
    public App(ShapeVisitor  sv){
        this.sv = sv;
    }
    public static void Process(Shape shape){
        //两处多态
        rec.Accept(sv);
    }
}

public static void Main(){
    App app = new App(new MyShapeVisitor());
    app.Process(new Line());
}

22 Strategy 策略 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-15 上午12:49‎

定义一系列算法,把他们一个个封装起来,并且使他们可相互替


对象可能经常需要使用多种不同的算法,经常改变
运行时根据需要透明地更改对象的方法

Context                           Strategy
                   ConcreteStrategyA

Strategy模式提供了用条件判断语句以外的另一种选择,消除
条件判断语句





enum CartType{ A, B, C }
class Cart{
    public void Process(CartType ct){
        if (ct == CartType.A){
            ProcessA();
        }
        else if (ct == CartType.B){
            ProcessB();
        }
        else if (ct == CartType.C){
            ProcessC();
        }
    }
    protected virtual void ProcessA(){    }
    protected virtual void ProcessB(){    }
    protected virtual void ProcessC(){    }
}
换。该模式使得算法可以独立于使用它的client而变化



//表达算法抽象
public interface IProcessStrategy{
    void Process();
}
public class ProcessStrategyA :IProcessStrategy{
    void IProcessStrategy.Process(){    }
}
public class ProcessStrategyB :IProcessStrategy{
    void IProcessStrategy.Process(){    }
}
public class ProcessStrategyC :IProcessStrategy{
    void IProcessStrategy.Process(){    }
}
class Cart{
    IProcessStrategy ps;
    
    public Cart(IProcessStrategy ps){
        this.ps = ps;
    }

    public void Somemethod1(){
        ps.Process();
    }
    public void Somemethod2(){
        ps.Process();
    }
}

public static void Main(){
    Cart cart = new Cart(new ProcessStrategyC());
    
}

21 State 状态 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-14 下午9:16‎

Definition : Allow an object to alter its behavior when its internal
允许一个对象在其内部状态改变是改变它的行为。从而使对象看起

对象拥有不同的状态,往往会有不同的行为
子类化支持改变

enum DocumentState{ ReadOnly, Editable }
public class Document{
    DocumentState state;
    public void Handle(){
        if (state == DocumentState.ReadOnly){
        }
        else if (state == DocumentState.Editable){            
        }
    }
}
state changes. The object will appear to change its class.
来似乎修改了其行为


abstract class StatedDocument{//抽象类--表达状态及依赖状态的行为
    abstract void Handler1();
    abstract void Handler2();
    abstract void Handler3();
    
    public abstract StatedDocument Next{//状态更改
        get;
        set;
    }
}

public class Document{//主逻辑
    StatedDocument sDoc;
    public void SetStatedDocument(StatedDocument sDoc){
        this.sDoc = sDoc;
    }
    public void Handle1(){
        sDoc.Handle1();
        sDoc = sDoc.Next;//状态更改
    }
    public void Handle2(){
        sDoc.Handle2();
    }
    public void Handle3(){
        sDoc.Handle3();
    }
}

public class ReadOnlyDocument : StatedDocument{
    public override viod Handle1(){    }
    public override viod Handle2(){    }
    public override viod Handle3(){    }
}
public class EditableOnlyDocument : StatedDocument{
    public override viod Handle1(){    }
    public override viod Handle2(){    }
    public override viod Handle3(){    }
}

20 Memento 备忘录 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-14 下午7:37‎

Definition : Without violating encapsulation, capture and 
restored to this state later.
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象态


对象状态的回溯

    Originator       -->            Memonto
   (SetM,CreateM)

class Rectangle : ICloneable{
    int x; int y;
    int width; int height;
    public void SetValue(Rectangle r){    }
    public object Clone(){
        return this.MemberwieseClone();
    }
    public Rectangle(int x, int y, int width, int height){    ...    }
    public void MoveTo(Point p){    }
    public void ChangeWidth(int width){    }
    public void ChangeHeight(int height){    }
    public void Draw(Graphic graphic){    }
}

class GraphicsSystem{
    //原发器对象--有必要对自身状态进行保存和恢复
    Rectangle r = new Rectangle(0, 0, 10, 10);
    //备忘录对象--保存原发器对象的状态,但不支持其操作
    Rectange rSaved = new Rectangle(0, 0, 10, 10);

    public void Process(Rectangle r){
        rSaved = r.Clone();
    }

    public static Restore_Click(object sender, EventArgs e){
        r.SetValue(rSaved);
    }
}


externalize an object's internal state so that the object can be

之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状




class Rectangle{
    int x; int y;
    int width; int height;

    public Rectangle(int x, int y, int width, int height){    ...    }
    public void MoveTo(Point p){    }
    public void ChangeWidth(int width){    }
    public void ChangeHeight(int height){    }
    public void Draw(Graphic graphic){    }
    
    public RectangleMemoto CreateMemento(){
        RectangleMemoto rm = new RectangleMemoto ();
        rm.SetValue(....);
        return rm;
    }
    public void Restore(RectangleMemoto rm){
        this.x = rm.x;
        ......
    }
}

class RectangleMemoto{
    internal int x; internal int y;
    internal int width; internal int height;
    internal void SetValue(int x, int y, int width, int height){    ...    }
}

class GraphicSystem{
    //原发器对象--有必要对自身状态进行保存和恢复
    Rectangle r = new Rectangle(0, 0, 10, 10);
    //备忘录对象--保存原发器对象的状态,但不支持其操作
    RectangleMemoto rSaved = new RectangleMemoto();
    public void Process(){
        rSaved = r.CreateMemento();
    }

    public static Restore_Click(object sender, EventArgs e){
        r.Restore(rSaved);
    }
}


19 Chain of Responsibility 职责链 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-14 下午5:53‎

Definition : Avoid coupling the sender of a request to its receiver by  the receiving objects and pass the request along the chain
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之
直到有一个对象处理它为止

一个请求可能被多个对象处理,但是每个请求在运行是只能有一个接受者


client                                       Handler(successor指针)
                            ConcreteHandler1       ConcreteHandler2

aClient (aHandler)---> aConcreteHandler(successor)   -->....



abstract class BaseHandler{
    public abstract void ShouldHandleRequest();
    public abstract void HandleRequest(Request request);
}
public class AHandler : BaseHandler{
    public override void HandleRequest(Request request){
    }
}

public class BHandler : BaseHandler{
    public void HandleRequest(Request request){
    }
}

public class Sender{
    public void Process(){
        Request request = new Request();
        //耦合
        List<BaseHandler> list = new List<BaseHander>();
        list.Add(new AHandler());
        list.Add(new BHandler());
        foreach(BaseHandler handler in list){
            if (handler.ShouldHandleRequest()){
                handler.HandleReqest();
            }
        }
    }
}

链条太长的话,太慢
末尾。。。
giving more than one object a chance to handle the request. Chain
until an object handles it.
间的耦合关系将这些对象连成一条链,并沿着这条链条传递请求,


abstract class BaseHandler{
    public BaseHandler(BaseHandler handler){
        next = handler;
    }
    protected abstract void ShouldHandleRequest();
    public virtual void HandleRequest(Request request){
        if (this.next != null){
            this.next.HandleRequest(request);
        }
    }
    
    BaseHandler next;
    public BaseHandler Next{
        get{
            return this.next;
        }
        set{
            this.next = value;
        }
    }
}

public class AHandler : BaseHandler{
    public AHandler(BaseHandler next) : base(next({    }
    public abstract void ShouldHandleRequest(){    }

    public override void HandleRequest(Request request){
        if (this.ShouldHandleRequest()){
            //自己处理
        }
        else{
            base.HandleRequest(request);
        }
    }
}

public class BHandler : BaseHandler{
    public BHandler(BaseHandler next) : base(next({    }
    protected override void ShouldHandleRequest(){    }

    public override void HandleRequest(Request request){
        if (this.ShouldHandleRequest()){
            //自己处理
        }
        else{
            base.HandleRequest(request);
        }
    }
}

public class Sender{
    public void Process(BaseHandler bh){
        Request request = new Request();
        bh.HandlerRequest(request);
    }
}
public static void Main(){
        BaseHandler h1 = new AHandler(null);
        BaseHandler h2 = new BHandler(h1);
        Sender s = new Sender();
        s.Process(h2);
}

18 Observer 观察者 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-13 下午10:21‎‎   [ 更新时间:‎‎2009-4-14 上午7:37‎‎ ]

Definition:Define a one-to-many dependency between objects so  and updated automatically
为某些对象建立一种通知依赖关系--一个对象的状态发生改变,所

//Version 1.0
public class ATM{
    BankAccount bankAccount;
    public void Process(int data){
        bankAccount.Withdraw(data);
    }
}
public class BankAccount{
    Emailer emailer;//紧耦合
    Mobile mobile;//紧耦合

    public void Withdraw(int data){
        //...

        //通知
        emailer.SendEmailer(usermail);
        mobile.SendNotification(phoneNumber);
    }
}

public class Emailer{
    public void SendEmail(string to){
        
    }
}

public class Mobile{
    public void SendNotification(string phoneNumber){
    }
}

---------------------------------------------------------
Version2.0

public class BankAccount{
    //单个时:IAccountObserver emailer;//弱依赖
    //多个:
    List<IAccountOberver> ol = new ArrayList<IAccountOberver>();

    public void Withdraw(int data){
        //...
        //通知
        UserAccountArgs args = new UserAccountArgs ();
        foreach(IAccountOberver ao in ol){
            ao.Update(args);
        }
    }

    public void AddObserver(IAccountOberver ao){
        ol.Add(ao);
    }
    public void RemoveObserver(IAccountOberver ao){
        ol.Remove(ao);
    }
}


public interface IAccountObserver{
    void Update(UserAccountArgs args);
}

public class Emailer : IAccountObserver{
    public void Update(UserAccountArgs args){
        string  toAddress = args.ToAddress;
        //...
    }
}

public class Mobile: IAccountObserver{
    public void Update(UserAccountArgs args){
        string  toPhoneNumber = args.PhoneNumber;
        //...
    }
}

Observer使得我们可以独立地改变目标与观察者
Event   委托



that when one object changes state, all its dependents are notified

有的依赖对象都将得到通知


Subject                          --->                Observer
   
ConcreteSubject             <---              ConcreteObserver



Version3.0
public abstract class Subject{
    List<IAccountOberver> ol = new ArrayList<IAccountOberver>();
   
    protected virtual void Notify(UserAccountArgs args){
        foreach(IAccountOberver ao in ol){
            ao.Update(args);
        }
    }

    public void AddObserver(IAccountOberver ao){
        ol.Add(ao);
    }
    public void RemoveObserver(IAccountOberver ao){
        ol.Remove(ao);
    }
}

public class BankAccount : Subject{
 
    public void Withdraw(int data){
        //...
        //通知
        UserAccountArgs args = new UserAccountArgs ();
        Notify(args);
    }
}


public interface IAccountObserver{
    void Update(UserAccountArgs args);
}

public class Emailer : IAccountObserver{
    public void Update(UserAccountArgs args){
        string  toAddress = args.ToAddress;
        //...
    }
}

public class Mobile: IAccountObserver{
    public void Update(UserAccountArgs args){
        string  toPhoneNumber = args.PhoneNumber;
        //...
    }
}



//Version 4.0  Event版
public delegate void AccountChangeEventHandler(
    object sender, AccountChangeEventArgs args);

public class BankAccount : Subject{
      public event AccountChangeEventHandler AccountChange;
    public void Withdraw(int data){
        //...
        //通知
        UserAccountArgs args = new UserAccountArgs ();
        Notify(args);
    }
    protected virtual OnAccountChange(AccountCEA args){
        if(AccountChange != null){
            AccountChange (args)
        }
    }
}

public class Emailer{
    public void Update(object sender, UserAccountArgs args){
        string  toAddress = args.ToAddress;
        //...
    }
}

public static void Main(){
    BankAccount ba = new BankAccount();
    Emailer emailer = new Emailer();
    ba.AccountChange += new AccountChangeEventHandler(
                emailer.Update)
}


17 Iterator 迭代器 notes

发布者:Bowen Gu,发布时间:‎‎2009-4-13 下午8:13‎‎   [ 更新时间:‎‎2009-4-13 下午10:08‎‎ ]

Definition : Provide a way to access the elements of an aggregate
集合内部结构与外部访问

    Aggregate(集合结构)             client               Iterator
    ConcreteAggregate                                ConcreteIterator

public interface IEnumerable {
    IEnumerator GetEnumerator();
}
public interface IEnumerator{
    Object Current { get; }
    bool MoveNext();
    void Reset();
}

public class MyCollection : IEnumerable{
    int[] items;
    public MyCollection(){
        items = new int[5]{};
    }

    public IEnumerator GetEnumerator(){
        return new MyEnumerator(this);
    }
    private class MyEnumerator : IEmuerator{
        int nIndex; MyCollection collection;
        public MyEnumerator(MyCollection mc){
            this.collection = mc;
            nIndex = -1;
        }
        public bool MoveNext(){
            nIndex++;
            return (nIndex < collection.Items.GetLength(0));
        }
        public int Current{
            get{    return collection.Items[nIndex];    }
        }

    }
}

public static void Main(){
    MyCollection mc = new MyCollection();
    foreach(int i in mc){
        Console.WriteLine(i);
    }
    //以下同上面等价,
    IEnumerator iterator = mc.GetEnumerator();
    while (
iterator .MoveNext()){
        int i = (int)
iterator .Current;
        Console.WriteLint(i);
    }

}
object sequentially without exposing its underlying representation.








.net 2.0
public class MyCollection : IEnumerable{
    int[] items;
    public MyCollection(){
        items = new int[5]{};
    }

    public IEnumerator GetEnumerator(){
        for (int i=0; i<5;i++){
            yield return items[i];
        }

    }
}

‹ 上一页    1-10/26    下一页 ›

蛰伏是另一段旅程的开始,人生总有浮云蔽日时,若能善用时光,蓄劲待发,静待云轻日开,则生命的甘泉,终有奔涛流涌、万里清畅的一天。

MSN
   
MAIL
   
   

212 天前是
五一

232 天前是
太湖两日游