示例名称:超级递送员
示例说明:定义基类(BaseDelivery)和虚方法(Deliver),定义继承自该基类的三个子类(MilkDelivery、NewspaperDelivery和CarDelivery),重写基类的虚方法(Deliver)。
示例类图:

关键部分说明

BaseDelivery
using System;

namespace
 Delivery
{
    
public class
 BaseDelivery
    
{
        
public virtual void
 Deliver()
        
{
            Console.WriteLine(
"我是早晨的送递员"
);
        }

    }

}

Deliver是虚方法,子类需要重写它。

MilkDelivery、NewspaperDelivery和CarDelivery
using System;

namespace
 Delivery
{
    
public class
 MilkDelivery : BaseDelivery
    
{
        
private
 BaseDelivery _delivery;

        
public
 MilkDelivery(BaseDelivery delivery)
        
{
            _delivery 
=
 delivery;
        }


        
public override void Deliver()
        
{
            _delivery.Deliver();
            Console.WriteLine(
"我送来牛奶!"
);
        }

    }

}



using System;

namespace
 Delivery
{
    
public class
 NewspaperDelivery : BaseDelivery
    
{
        
private
 BaseDelivery _delivery;
        
public
 NewspaperDelivery(BaseDelivery delivery)
        
{
            _delivery 
=
 delivery;
        }

        
public override void Deliver()
        
{
            _delivery.Deliver();
            Console.WriteLine(
"我送来了报纸!"
);
        }

    }

}



using System;

namespace
 Delivery
{
    
public class
 CarDelivery:BaseDelivery
    
{
        
private
 BaseDelivery _delivery;
        
public
 CarDelivery(BaseDelivery delivery)
        
{
            _delivery 
=
 delivery;
        }

        
public override void Deliver()
        
{
            _delivery.Deliver();
            Console.WriteLine(
"我还送来了你买的小汽车,梦想成真了吧,哈哈!"
);
        }

    }

}


这三个类分别继承了BaseDelivery(is a的关系),含有一个BaseDelivery类型的私有字段和一个BaseDelivery参数的构造方法,重写父类BaseDelivery的Deliver方法。

应用
using System;
using System.Collections.Generic;
using System.Text;

namespace Delivery
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            BaseDelivery baseDelivery 
= new BaseDelivery();
            MilkDelivery milkDelivery 
= new MilkDelivery(baseDelivery);
            NewspaperDelivery newsDelivery 
= new NewspaperDelivery(milkDelivery);
            CarDelivery carDelivery 
= new CarDelivery(newsDelivery);
            carDelivery.Deliver();
            Console.Read();
        }

    }

}

任何继承了BaseDelivery的子类都可以做为其它子类的构造函数的参数传递。即可实现对该子类的装饰(Decorator)。

运行结果


现在是不是很开心!
posted on 2010-02-22 16:53  yxbsmx  阅读(114)  评论(0编辑  收藏  举报