装饰模式-坦克大战-c#

本文介绍了一种设计模式——装饰模式,该模式允许在不改变对象结构的前提下,动态地给对象添加新的职责。通过装饰模式,可以更加灵活地为对象增加功能,相比生成子类的方式更具优势。文章通过.NET的示例代码详细展示了装饰模式的实现。

概要

 动态一个象添加一些外的职责。就增加功能来Decorator模式相比生成子灵活。

类图 

最简单的装模式

运行 

代码 

using System;

namespace 装饰模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Client client = new Client();
            client.main();
            Console.ReadLine();
        }
        interface IComponent
        {
            void operation();
        }
        class SortComponent : IComponent
        {
            public void operation()
            {
                Console.WriteLine("发射炮弹");
            }
        }
        class RunComponent : IComponent
        {
            public void operation()
            {
                Console.WriteLine("跑");
            }
        }
        abstract class Decorator : IComponent
        {
            public Decorator(IComponent component)
            {
                this.component = component;
            }
            private IComponent component;
            public void operation()
            {
                this.component.operation();
                addedBehaivor();
            }
            public abstract void addedBehaivor();
        }
        class ArmDecorator : Decorator
        {
            public ArmDecorator(IComponent component) : base(component){}

            public override void addedBehaivor()
            {
                Console.WriteLine("红外瞄准");
            }
        }
        class GpsDecorator : Decorator
        {
            public GpsDecorator(IComponent component) : base(component) { }

            public override void addedBehaivor()
            {
                Console.WriteLine("卫星定位");
            }
        }
        class Client
        {
            public void main()
            {
                SortComponent sortComponent = new SortComponent();
                ArmDecorator armDecorator = new ArmDecorator(sortComponent);
                GpsDecorator gpsDecorator = new GpsDecorator(armDecorator);
                gpsDecorator.operation();
            }
        }
    }
}

英语

component
adj. 组成的,构成的; n. 成分; 组件; [电子] 元件
operation
n. 操作; 经营; [外科] 手术; [数][计] 运算
decorator
n. 装饰者; 室内装潢师
concrete
adj. 混凝土的; 实在的,具体的; 有形的; vi. 凝结; vt. 使凝固; 用混凝土修筑;

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值