1、为什么使用设计模式?
使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性。
2、设计模式分成三类
(1)创建型设计模式:这些设计模式提供了一种在创建对象的同事隐藏了创建逻辑的方式,而不是使用new运算符直接实例化对象,这使得程序在判断对某个给定实例需要创建哪些对象时更加灵活。
(2)结构性设计模式:这些设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。
(3)行为型设计模式:这些设计模式特别关注对象之间的通信。
3、设计模式的六大原则
(1)开闭原则:对扩展开放,对修改关闭。在程序需要拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。因此需要使用到继承和抽象类
(2)里氏代换原则:任何基类出现的地方,子类一定可以出现替代父类。
(3)依赖倒转原则:这个是开闭原则的基础,依赖抽象而不依赖实现。
(4)接口隔离原则:使用多个隔离的接口,比使用单个接口要好,它强调降低依赖,降低耦合。
(5)迪米特-又称最少知道原则:一个类应该尽量降低与其他实体之间发生相互作用,使得系统功能模块相对独立。
(6)合成复用原则:尽量使用合成/聚合的方式,而不是继承。
4、常用的设计模式
(1)外观模式
假设我们应用显示的数据需要从很多不同的方式获取
public inteface RecallData {
List<Data> recall();
}
public class BaiduRecallData {
public List<Data> recall();
}
public class DouBanRecallData {
public List<Data> recall();
}
public class RealRecall{
public static void main(String[] args) {
List<RecallData> recallDataLsit = new ArrayList<RecallData>();
recallDataLsit .add(new BaiduRecallData());
recallDataLsit .add(new DouBanRecallData ());
for(RecallData recallData : recallDataList) {
recallData.recall();
}
}
}
(2)责任链模式
public class RealChain {
// 省略成员变量
public RealChain(List<Interceptor> interceptors, int index){
// 省略对成员变量赋值
}
public Response chain() {
// 主要是这里,获取下一个Interceptor传到当前的Interceptor里面
RealChain realChain = new RealChain(interceptors, index + 1);
Interceptor interceptor = interceptors.get(index);
return interceptor.intercept();
}
}
public interface Interceptor {
Response intercept(RealChain realChain);
}
public class AInterceptor implements Interceptor {
public Response intercept(RealChain realChain) {
// doSomeThing
return realChain.chain();
}
}
public class BInterceptor implements Interceptor {
public Response intercept(RealChain realChain) {
// doSomeThing
return realChain.chain();
}
}