装饰模式
从衣服装饰看起,就是把一个人不断包装。
第一个类:抽象类组成类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
abstract class Component
{
public abstract void show();
}
}
定义一个抽象展现函数。
第二个类:装饰类(继承抽象组成类、成员函数是其父类组成类)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Finery:Component
{
protected Component com;
public Finery(Component com)
{
this.com = com;
}
public override void show()
{
if(com!=null)
{
com.show();
}
}
}
}
第三个类:人物类(成员是其名字、成员函数是展现函数、继承装饰类)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Person : Component
{
private string name;
public Person(string name)
{
this.name = name;
}
public Person()
{
}
public override void show()
{
Console.WriteLine (name);
}
}
}
第四、五、六都是衣服类(继承装饰类)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Kt:Finery
{
public Kt(Component com) : base(com) { }
public override void show()
{
Console.WriteLine("穿了裤子");
base.show();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Shoe:Finery
{
public Shoe(Component com) : base(com) { }
public override void show()
{
Console.WriteLine("穿了鞋子");
base.show();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Ts : Finery
{
public Ts(Component com) : base(com) { }//初始化父类
public override void show()
{
Console.WriteLine("穿了T-shirt");
base.show();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Dx:Finery
{
public Dx(Component com) : base(com) { }//初始化父类
public override void show()
{
Console.WriteLine("穿了短袖");
base.show();
}
}
}
然后是测试类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("第一种方式");
Component Mrs = new Person("小王");
Component Kt = new Kt(Mrs);
Component Ts = new Ts(Kt);
Component Shoe = new Shoe(Ts);
Shoe.show();
Console.WriteLine("-------------------");
Console.WriteLine("第二种方式");
Component Dx = new Dx(new Kt(new Shoe(new Person("小李"))));
Dx.show();
//递归调用
}
}
}
注意多体会写法。
UML