装饰模式

Code
今天看了,装饰模式,可以对抽象的对象进行多次装饰,这样利于扩展装饰的类型,同时也可以动态的去扩充实际装饰对象的方法。根据自己的实际需要去选择装饰类型,增加了客户端的灵活性。
using System;


namespace xiaopeng.DH
{
    
//装饰的对象
    public class Person
    
{
        
public Person()
        
{ }
        
private string _name;

        
public Person(string name)
        
{
            
this._name = name;
        }


        
public virtual void Show()
        
{
            Console.WriteLine(
"装扮的{0}", _name);
        }

    }


    
//服饰类
    public class Finery : Person
    
{
        
protected Person component;

        
public void Decorate(Person component)
        
{
            
this.component = component;
        }


        
public override void Show()
        
{
            
if (this.component != null)
            
{
                
                
this.component.Show();
            }

        }

    }



    
public class TShirts : Finery
    
{
        
public override void Show()
        
{
            Console.Write(
" 大Txue ");
            
base.Show();
        }

    }


    
public class GigTrouser : Finery
    
{
        
public override void Show()
        
{
            Console.Write(
" 跨裤 ");
            
base.Show();
        }

    }


    
public class LeatherShoes : Finery
    
{
        
public override void Show()
        
{
            Console.Write(
" 球鞋 ");
            
base.Show();
        }

    }


    
class Person_run
    
{
        
static void Main(string[] args)
        
{
            Person peng 
= new Person("xiaopeng");

            Console.WriteLine(
"\n第一种装扮:");
            TShirts t1 
= new TShirts();
            GigTrouser t2 
= new GigTrouser();
            t1.Decorate(peng);
            t2.Decorate(t1);
            t1.Show();

            Console.WriteLine(
"\n第二种装扮:");

            LeatherShoes t3 
= new LeatherShoes();
            t3.Decorate(peng);
            t2.Decorate(t3);
       
            t2.Show();
        }

    }

}

示例代码
posted @ 2009-05-27 14:05  程晓鹏  阅读(241)  评论(0)    收藏  举报