模拟穿衣服场景
我们来看下面一个具体的案例:每个人一天起床之后都要穿衣服(来装饰自己),这是必不可少的,这样问题就来了,穿什么?按照什么顺序穿?
如何用程序方便的模拟这个场景的,代码如下:
/**
* 程序模拟一个人穿衣服的过程
* @author: qhyuan1992
*/
// 抽象接口,用来规范将要被附加一些操作的对象
interface People{
public void wear();
}
// 具体的对象,该对象将被附加一些额外的操作
class Jane implements People{
public void wear() {
System.out.println("今天该穿什么呢?");
}
}
// 装饰者类,持有一个将要被装饰的接口对象的实例
class Decorator implements People{
private People people;
public Decorator(People people) {
this.people = people;
}
public void wear() {
people.wear();
}
}
// 具体的装饰者类,负责给增加附加的操作:穿衬衫
class DecoratorShirt extends Decorator{
public DecoratorShirt(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿个衬衫");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿西服
class DecoratorSuit extends Decorator{
public DecoratorSuit(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿个西服");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿T-Shirt
class DecoratorTShirt extends Decorator{
public DecoratorTShirt(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿个T-Shirt");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿裤子
class DecoratorPants extends Decorator{
public DecoratorPants(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("穿裤子");
}
}
// 具体的装饰者类,负责给增加附加的操作:穿鞋子
class DecoratorShoes extends Decorator{
public DecoratorShoes(People people) {
super(people);
}
public void wear() {
super.wear();
System.out.println("鞋子");
}
}
public class DecoratorTest {
public static void main(String[] args) {
People p1 = new Decorator