结构型设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。
适配器模式
类自己的接口包裹在一个已存在的类中,让因接口不兼容而不能在一起工作的类工作在一起。
类适配器:继承方式
对象适配:构造函数传递
接口适配方式:直接按照需求,调用不同的实现
应用场景
1、我们在使用第三方的类库,或者说第三方的API的时候,我们通过适配器转换来满足现有系统的使用需求。
2、我们的旧系统与新系统进行集成的时候,我们发现旧系统的数据无法满足新系统的需求。
装饰器模式
对已经存在的某些类进行装饰,以此来扩展一些功能。
扫描二维码关注公众号,回复:
5870485 查看本文章
//房屋装饰类
public class HouseDecorate implements House {
private House house;
public HouseDecorate(House house){
this.house=house;
}
@Override
public void run() {
house.run();
}
}
public class HouseDecorateImpl extends HouseDecorate {
public HouseDecorateImpl(House house) {
super(house);
}
@Override
public void run() {
super.run();
System.out.println("贴上墙纸..");
}
}
客户端调用
public class ClientTest {
public static void main(String[] args) {
HouseImpl houseImpl = new HouseImpl();
houseImpl.run();
System.out.println("###新增贴上墙纸..###");
HouseDecorate houseDecorate = new HouseDecorateImpl(houseImpl);
houseDecorate.run();
}
}
与代理模式:
1、装饰是添加功能,代理是控制用户访问。
2、装饰是原始对象,代理是一个构造的对象,可以隐藏原有的属性。
代理模式
静态代理-jdk动态代理-CGLIB动态代理
https://mp.csdn.net/postedit/89068761
外观模式(就是使用一个方法,封装多个方法的调用)
隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。
提供单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。
public class Computer {
AliSmsService aliSmsService;
EamilSmsService eamilSmsService;
WeiXinSmsService weiXinSmsService;
public Computer() {
aliSmsService = new AliSmsServiceImpl();
eamilSmsService = new EamilSmsServiceImpl();
weiXinSmsService = new WeiXinSmsServiceImpl();
}
public void sendMsg() {
aliSmsService.sendSms();
eamilSmsService.sendSms();
weiXinSmsService.sendSms();
}
}
public class Client {
public static void main(String[] args) {
// AliSmsService aliSmsService= new AliSmsServiceImpl();
// EamilSmsService eamilSmsService= new EamilSmsServiceImpl();
// WeiXinSmsService weiXinSmsService= new WeiXinSmsServiceImpl();
// aliSmsService.sendSms();
// eamilSmsService.sendSms();
// weiXinSmsService.sendSms();
new Computer().sendMsg();
}
}