装饰者模式

何为装饰者模式?

     装饰者模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,提供比继承更多的灵活性。动态地给对象添加功能;

    

View Code
/*
 * 由SharpDevelop创建。
 * 用户: 秦仕川
 * 日期: 2013-2-2
 * 时间: 16:22
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 
*/
using System;

namespace 装饰者模式
{
    /// <summary>
    
/// Description of Duck.
    
/// </summary>
    public  class Animal
    {
        private string _AnimalName;
        
        public string AnimalName {
            get { return _AnimalName; }
            set { _AnimalName = value; }
        }
        public  void Walk(){
            Console.WriteLine(this.AnimalName+"Walk");
        }
        public virtual void DecaratorMethod(){
            
        }
    }
    public class WaterDuck:Animal{
        public WaterDuck(){
            this.AnimalName="水鸭子";
        }
    }
    public class WildDuck:Animal{
        public WildDuck(){
            this.AnimalName="野鸭子";
        }
    }
    public class Fish:Animal{
        public Fish(){
            this.AnimalName="";
        }
    }
     
    public class FlyDecarator:Animal{
        private Animal _animal;
        
        public FlyDecarator(Animal an){
            _animal=an;
        }
        public override void DecaratorMethod(){
            _animal.DecaratorMethod();
            Console.WriteLine("fly");
        }
    }
    public class SwimDecarator:Animal{
        private Animal _animal;
        
        public SwimDecarator(Animal an){
            _animal=an;
        }
        public override void DecaratorMethod(){
            _animal.DecaratorMethod();
            Console.WriteLine("Swim");
        }
    }
}

    装饰类,去装饰对象,一层装饰一层,达到功能添加的效果.


using System;

namespace 装饰者模式
{
    class Program
    {
        public static void Main(string[] args)
        {
            Fish fish=new Fish();
            SwimDecarator sw=new SwimDecarator(fish);
            sw.DecaratorMethod();
            
            WildDuck wd=new WildDuck();
            SwimDecarator swd=new SwimDecarator(wd);
            FlyDecarator fly=new FlyDecarator(swd);
            fly.DecaratorMethod();
            
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}
 

posted @ 2013-02-03 13:38  [秦时明月]  阅读(261)  评论(2编辑  收藏  举报