装饰者模式1 vae -> oae
抽象类
public abstract class People {
protected abstract String desc();
protected abstract int weight();
}
vae
public class Vae extends People {
@Override
protected String desc() {
return "I am vae.";
}
@Override
protected int weight() {
return 120;
}
}
uae
public class Uae extends Vae {
@Override
protected String desc() {
return super.desc() + " eat more. become uae.";
}
@Override
protected int weight() {
return super.weight() + 20;
}
}
oae
public class Oae extends Uae {
@Override
protected String desc() {
return super.desc() + " eat more and more. become oae.";
}
@Override
protected int weight() {
return super.weight() + 40;
}
}
测试类
public class Test {
public static void main(String[] args) {
People people = new Vae();
System.out.println(people.desc() + " " + people.weight() + "斤.");
people = new Uae();
System.out.println(people.desc() + " " + people.weight() + "斤.");
people = new Oae();
System.out.println(people.desc() + " " + people.weight() + "斤.");
}
}
执行结果
I am vae. 120斤.
I am vae. eat more. become uae. 140斤.
I am vae. eat more. become uae. eat more and more. become oae. 180斤.
装饰者模式2 上帝创造你的女朋友
人类抽象类,你女朋友是个人
public abstract class Human {
public abstract String desc();
}
原始的女朋友
public class YourGirlFriend extends Human {
@Override
public String desc() {
return "上帝创造你的女朋友...\n";
}
}
上帝的装饰器
public abstract class AbstractDecorator extends Human{
private Human human;
public AbstractDecorator(Human human) {
this.human = human;
}
@Override
public String desc() {
return this.human.desc();
}
}
上帝加的佐料1 – 颜值
public class AppearanceDecorator extends AbstractDecorator {
public AppearanceDecorator(Human human) {
super(human);
}
@Override
public String desc() {
return super.desc() + "颜值+5..\n";
}
}
上帝加的佐料2 – 饭量
public class AppetiteDecorator extends AbstractDecorator {
public AppetiteDecorator(Human human) {
super(human);
}
@Override
public String desc() {
return super.desc() + "饭量+10..\n";
}
}
上帝的佐料3 – battle能力
public class QuarrelDecorator extends AbstractDecorator {
public QuarrelDecorator(Human human) {
super(human);
}
@Override
public String desc() {
return super.desc() + "抬杠+1000000..\n";
}
}
测试类
public class Test {
public static void main(String[] args) {
Human youGirlFriend = new YourGirlFriend();
youGirlFriend = new AppearanceDecorator(youGirlFriend);
youGirlFriend = new AppetiteDecorator(youGirlFriend);
youGirlFriend = new QuarrelDecorator(youGirlFriend);
System.out.println(youGirlFriend.desc());
}
}
运行效果
上帝创造你的女朋友...
颜值+5..
饭量+10..
抬杠+1000000..