Core Design Patterns(1) Decorator 装饰模式

VS 2008

当我们需要给一个已有的对象动态的附加状态或行为时,使用装饰模式。
装饰模式的要点是:装饰类实现了最初的被装饰类,并且包含了被装饰类的一个实例

1. 模式静态类图



2. 应用

    从一只可以写的Pen开始
    把它装饰成有颜色的笔、粗线的笔,甚至可以是有颜色且粗线的笔



IWritable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Decorator.BLL {
    
interface IWritable {
        
void Write();
    }

}

Pen

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Decorator.BLL {
    
class Pen : IWritable {
        
IWritable Members
    }

}

ColoredPen

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Decorator.BLL {
    
class ColoredPen : IWritable {

        IWritable component 
= null;
        
string color = string.Empty;

        
public ColoredPen(IWritable component, string color) {
            
this.component = component;
            
this.color = color;
        }


        
IWritable Members

        
public void SetColor(string color) {
            
this.color = color;
        }

    }

}

BoldPen

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Decorator.BLL {
    
class BoldPen : IWritable {

        IWritable component 
= null;
        
int borderWidth = 0;

        
public BoldPen(IWritable component, int borderWidth) {
            
this.component = component;
            
this.borderWidth = borderWidth;
        }


        
IWritable Members

        
public void SetBorderWidth(int borderWidth) {
            
this.borderWidth = borderWidth;
        }

    }

}

Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.Decorator.BLL;

namespace DesignPattern.Decorator {
    
class Program {
        
static void Main(string[] args) {
            IWritable p 
= new Pen();
            p.Write();
            Console.WriteLine();

            ColoredPen coloredPen 
= new ColoredPen(p, "red");
            coloredPen.Write();
            Console.WriteLine();

            BoldPen boldPen 
= new BoldPen(p, 2);
            boldPen.Write();
            Console.WriteLine();

            BoldPen coloredAndBoldPen 
= new BoldPen(coloredPen, 4);
            coloredAndBoldPen.Write();
        }

    }

}

posted on 2008-02-24 22:05  Tristan(GuoZhijian)  阅读(539)  评论(1编辑  收藏  举报