区别
装饰者模式:
就是为了给装饰者的方法增强,单纯的是为了在装饰者方法上增加其他功能。是继承的一种替代方案,可以理解为 在不改变接口的前提下,动态扩展对象的功能
例子:孙悟空七十二变
孙悟空有七十二般变化,他的每一种变化都给他带来一种附加的本领。他变成鱼儿时,就可以到水里游泳;他变成雀儿时,就可以在天上飞行。而不管悟空怎么变化,在二郎神眼里,他永远是那只猢狲。
动态代理:
给一个对象提供一个代理对象,并有代理对象来控制对原有对象的引用;被代理的对象难以直接获得或者是不想暴露给客户端
例子:孙悟空扮演并代替高家三小姐
孙悟空扮演高家三小姐,所以可以说孙悟空与高家三小姐具有共同的接口。
如果猪八戒只想见见高家三小姐的娇好面容,或者谈谈天说说地,那么高家三小姐的“代理”孙悟空是允许的,但猪八戒想亲亲嘴,要搞弓虽奸,那么是不行的。
装饰者模式
/**
* 首先定义一个接口来规范咖啡.
*/
interface Coffee {
void coffee();
void catCoffee();
}
/**
* 选择一个类来时间接口
*/
class CoffeeImpl implements Coffee {
public void coffee(){
System.out.println("咖啡");
}
public void catCoffee(){
System.out.println("猫shi咖啡");
}
}
/*
* 装饰类
* 在给黑咖啡添加调味品之前,我们先定义一个类,这个类是所有添加调味品咖啡的父类,进行包装
*/
public class CoffeeWrapper implements Coffee {
private Coffee cof;
public CoffeeWrapper(Coffee cof){
this.cof = cof;
}
public void coffee(){
cof.coffee();
}
public void catCoffee() {
cof.catCoffee();
}
/**
* 加糖咖啡
*/
public class Sugar extends CoffeeWrapper {
public Sugar(Coffee cof) {
super(cof);
}
public void coffee(){
super.coffee();
System.out.println("加糖");
}
}
}
public class Test {
/**
* 装饰者测试
* @param args
*/
public static void main(String[] args) {
Coffee coffee = new CoffeeImpl();
Coffee su = new TestConffee().new Milk(coffee);
su.coffee();
}
}
动态代理
/**
* 首先定义一个接口来规范咖啡.
*/
interface Coffee {
void coffee();
void catCoffee();
}
/**
* 选择一个类来时间接口
*/
class CoffeeImpl implements Coffee {
public void coffee(){
System.out.println("咖啡");
}
public void catCoffee(){
System.out.println("猫shi咖啡");
}
}
/**
* 动态代理
*/
public class CoffeeHander implements InvocationHandler
{
public Coffee coffee;
public CoffeeHander(Coffee coffee){
this.coffee = coffee;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("coffee".equals(method.getName())) {
System.out.println("欢迎光临");
//这里我们使用了method的invoke来执行waiterProxy中的方法。
Object object = method.invoke(coffee, args);
System.out.println("谢谢光临");
return object;
}else {
//对UserService的每一方法的前后置增强
System.out.println("addUser before.........");
Object invoke = method.invoke(coffee, args);
System.out.println("addUser after.........");
return invoke;
}
}
public static void main(String[] args) {
Coffee coffeeImp = new CoffeeImpl();//一般你是看不见这一步的
Coffee coffeeProxy = (Coffee)Proxy.newProxyInstance(coffeeImp.getClass().getClassLoader(),
coffeeImp.getClass().getInterfaces(), new CoffeeHander(coffeeImp));
coffeeProxy.coffee();
coffeeProxy.catCoffee();
}
}
引用
「1」 https://blog.csdn.net/qq_32101859/article/details/50733543