装饰器模式start
- 有一个接口
ISomeService
package pattern.decorator;
/**
* @author futao
* Created on 18-8-21-上午6:06.
*/
public interface ISomeService {
String doSome(String parameter);
}
- 有一个实现类(相当于原始代码--目标类)
SomeService
package pattern.decorator;
/**
* @author futao
* Created on 18-8-21-上午6:07.
*/
public class SomeService implements ISomeService {
@Override
public String doSome(String parameter) {
return parameter;
}
}
- 运行结果:
@Test
public void test18() {
ISomeService iSomeService = new SomeService();
String some = iSomeService.doSome("woqu hhh");
System.out.println(some);
}
>>> woqu hhh
- 新需求:要把所有的输出变成大写,并且原来的类,业务逻辑
SomeService
不可改变 - 装饰器类:
SomeServiceDecorator
,对SomeService
进行增强
package pattern.decorator;
/**
* @author futao
* Created on 18-8-21-下午4:58.
* 装饰器,增强SomeService
* 1.继承同一个接口
* 2.在装饰器类中添加一个构造方法--在构造方法中添加需要增强的那个类的引用(装饰器类中要有目标对象作为成员变量,且目标对象是通过带参构造器传入的)
*/
public class SomeServiceDecorator implements ISomeService {
ISomeService iSomeService;
@Override
public String doSome(String parameter) {
//先执行原有的业务逻辑
String some = iSomeService.doSome(parameter);
//对执行结果进行增强
return some.toUpperCase();
}
/**
* 要求一定要传入需要增强(装饰的那个类-对象)
*
* @param iSomeService
*/
public SomeServiceDecorator(ISomeService iSomeService) {
super();
this.iSomeService = iSomeService;
}
}
- 使用
@Test
public void test18() {
//目标对象
SomeService someService = new SomeService();
//装饰器
ISomeService iSomeService = new SomeServiceDecorator(someService);
//面向接口编程
String some = iSomeService.doSome("woqu hhh");
System.out.println(some);
}
7.高级用法:用一个基类去实现接口,在基类中执行目标类的业务逻辑。通过继承基类的方式增强目标类,每个子类可以实现各自的增强,将增强逻辑细分,每个子类增强一个小功能。
装饰器模式end
代理模式start
1.面向接口编程之业务接口:ISomeService
package pattern.proxy;
/**
* @author futao
* Created on 18-8-21-下午6:58.
*/
public interface ISomeService {
String doSome();
String doOther();
}
2.业务逻辑类: SomeService
package pattern.proxy;
/**
* @author futao
* Created on 18-8-21-下午7:01.
* 业务逻辑
*/
public class SomeService implements ISomeService {
@Override
public String doSome() {
return "abcde";
}
@Override
public String doOther() {
return "今晚打老虎";
}
}
- 代理类:
SomeServiceProxy
package pattern.proxy;
import com.alibaba.fastjson.JSONObject;
/**
* @author futao
* Created on 18-8-21-下午6:58.
* 代理类
*/
public class SomeServiceProxy implements ISomeService {
//代理对象---通过实例化new的方式直接创建
private ISomeService target = new SomeService();
@Override
public String doSome() {
return target.doSome();
}
/**
* 隐藏一些逻辑
*
* @return
*/
@Override
public String doOther() {
//可以加上一些控制逻辑
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", "无权限访问此资源.");
return JSONObject.toJSONString(jsonObject);
}
}
4.使用:
@Test
public void test19(){
//不要实例化目标对象,没有暴露目标对象
pattern.proxy.ISomeService iSomeService=new SomeServiceProxy();
System.out.println(iSomeService.doSome());
System.out.println(iSomeService.doOther());
}
>>> abcde
{"result":"无权限访问此资源."}
5. 总结:
装饰器模式是为了增强目标对象
代理模式是为了保护隐藏目标对象
装饰器模式中的目标对象是通过带参构造器传入
代理模式是在代理类中直接创建
代理模式end