随笔-42  评论-125  文章-0  trackbacks-4
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) 阅读(221) 评论(1)  编辑 收藏 所属分类: Design Pattern

评论:
#1楼  2008-05-13 15:35 | 吉日嘎拉 [未注册用户]
在学习你的这些,挺不错的,想从头,学到尾。
  回复  引用    

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  博客园首页

  新闻频道

  社区

  小组

  博问

  网摘

  闪存

  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-02-25 22:03 编辑过
成果网帮您增加网站收入


相关链接: