设计模式学习记录:一句话+代码体会设计模式。
九大常用设计模式
单例模式:https://blog.csdn.net/qq_37902949/article/details/87903569
简单工厂/静态工厂方法模式:https://blog.csdn.net/qq_37902949/article/details/87931684
工厂方法模式:https://blog.csdn.net/qq_37902949/article/details/87931610
代理模式:https://blog.csdn.net/qq_37902949/article/details/87931864
模板方法模式:https://blog.csdn.net/qq_37902949/article/details/87931912
观察者模式:https://blog.csdn.net/qq_37902949/article/details/87931995
适配器模式:https://blog.csdn.net/qq_37902949/article/details/87931940
装饰者模式:https://blog.csdn.net/qq_37902949/article/details/87931800
策略模式:https://blog.csdn.net/qq_37902949/article/details/87932047
适配器模式:将一个类的接口转换成客户希望的另外一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器有:类适配器,对象适配器,接口适配器。。。
一个USB接口与网卡接口 转换 的例子体会适配器模式。
/**
* USB接口
*/
public interface USB {
void useUsb();
}
/**
* USB接口实现
*/
public class UsbImpl implements USB {
@Override
public void useUsb() {
System.out.println("使用了USB接口");
}
}
/**
* Wlan接口
*/
public interface Wlan {
void useWlan();
}
/**
* 无线网接口实现
*/
public class WlanImpl implements Wlan {
@Override
public void useWlan() {
System.out.println("使用Wlan接口");
}
}
类适配器
/**
* 类适配器
*/
public class Adapter extends WlanImpl implements USB {
@Override
public void useUsb() {
useWlan();
}
}
/**
* 类适配器测试
*/
public class TestClassAdapter {
public static void main(String[] args) {
// 创建USB到Wlan接口的适配对象
Adapter adapter = new Adapter();
adapter.useUsb();
}
}
对象适配器
/**
* 对象适配器
*/
public class USBToWlanAdapter implements USB {
private Wlan wlan;
public USBToWlanAdapter(Wlan wlan) {
this.wlan = wlan;
}
@Override
public void useUsb() {
wlan.useWlan();
}
}
/**
* 对象适配器测试
*/
public class TestObjectAdapter {
public static void main(String[] args) {
USBToWlanAdapter adapter = new USBToWlanAdapter(new WlanImpl());
adapter.useUsb();
}
}
接口适配器,自定义化操作更方便
/**
* 接口
*/
public interface FunctionInterface {
void optional1();
void optional2();
void optional3();
void optional4();
void optional5();
}
/**
* 接口适配类
*/
public abstract class AbstractFunctionInterface implements FunctionInterface {
@Override
public void optional1() {
// TODO Auto-generated method stub
}
@Override
public void optional2() {
// TODO Auto-generated method stub
}
@Override
public void optional3() {
// TODO Auto-generated method stub
}
@Override
public void optional4() {
// TODO Auto-generated method stub
}
@Override
public void optional5() {
// TODO Auto-generated method stub
}
}
/**
* 接口适配器,想重写哪个方法就哪个
*/
public class FunctionInterfaceImpl extends AbstractFunctionInterface {
@Override
public void optional3() {
// TODO Auto-generated method stub
}
@Override
public void optional4() {
// TODO Auto-generated method stub
}
}
设计模式是软件开发人员在软件开发过程中面临一般问题的解决方案。
设计模式还是要慢慢体会。。