装饰者模式的另一种思路
/** * @Auther: penghaozhong
* @Date: 2020-05-21 15:53
*/
public interface Test {
String say(String name);
}
public class Test1 implements Test {
private Test test;
public Test1(Test test) {
this.test = test;
}
@Override
public String say(String name) {
System.out.println("Test1");
return test.say(name);
}
}
public class Test2 implements Test {
private Test test;
public Test2(Test test) {
this.test = test;
}
@Override
public String say(String name) {
System.out.println("Test2");
return test.say(name);
}
}
public class Test3 implements Test {
private Test test;
public Test3(Test test) {
this.test = test;
}
@Override
public String say(String name) {
System.out.println("Test3");
return test.say(name);
}
}
public class TestA implements Test {
@Override
public String say(String name) {
return "TestA-" + name;
}
}
public class TestMain {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Set<Class<?>> wrapperClasses = Sets.newHashSet(Test1.class,Test2.class,Test3.class);
Test instance = new TestA();
if (CollectionUtils.isNotEmpty(wrapperClasses)) {
for (Class<?> wrapperClass : wrapperClasses) {
instance = (Test)wrapperClass.getConstructor(Test.class).newInstance(instance);
}
}
String heihe = instance.say("heihe");
System.out.println(heihe);
}
}
输出结果
以上是 装饰者模式的另一种思路 的全部内容, 来源链接: utcz.com/z/516631.html