实验七 装饰模式的应用(Java实现)
一、实验目的
- 掌握装饰模式(Decorator)的特点
- 分析具体问题,使用装饰模式进行设计。
二、实验内容和要求
“喜羊羊逃命”游戏:喜羊羊被灰太狼追,喜羊羊最多5条命,灰太狼每咬到喜羊羊一次,喜羊羊就要少一条命。在逃的过程中喜羊羊可以吃到三种苹果,吃“红苹果”可以给喜羊羊加上保护罩,吃“绿苹果”可以加快喜羊羊奔跑速度,吃“黄苹果”可以使喜羊羊趟着水跑。应用装饰模式,用C#或Java、C++控制台应用程序实现该设计。绘制该模式的UML图。
(提示:这个例子如果用类的继承来实现的话那可就麻烦了,你需要为喜羊羊派生321=6个子类(有保护罩的喜羊羊,奔跑速度加快的喜羊羊,会趟水的喜羊羊,既有保护罩又会趟水的喜羊羊,奔跑速度快且会趟水的喜羊羊,有保护罩且奔跑速度快的喜羊羊,有保护罩、奔跑速度快且会趟水的喜羊羊),如果使用装饰模式的那就不用派生诸多子类了,当喜羊羊每吃到一个苹果,我们就用装饰模式给喜羊羊加一个动态增加一个新功能即可。)
三、源代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
abstract class Appearance
{
public abstract void Show();
}
class Sheep : Appearance
{
private string name;
public Sheep(string name)
{
this.name = name;
}
public override void Show()
{
Console.WriteLine("{0}的效果:", name);
}
}
abstract class State : Appearance
{
protected Appearance component;
public void Decorate(Appearance component)
{
this.component = component;
}
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
class Effect1 : State
{
public override void Show()
{
base.Show();
Console.Write("保护罩 ");
}
}
class Effect2 : State
{
public override void Show()
{
base.Show();
Console.Write("奔跑加速 ");
}
}
class Effect3 : State
{
public override void Show()
{
base.Show();
Console.Write("会趟水 ");
}
}
static void Main(string[] args)
{
Sheep sp = new Sheep("喜羊羊");
Effect1 ef1 = new Effect1();
Effect2 ef2 = new Effect2();
Effect3 ef3 = new Effect3();
ef1.Decorate(sp);
ef2.Decorate(ef1);
ef3.Decorate(ef2);
ef3.Show();
Console.Read();
}
}