模板方法
模板方法模式:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的
重复代码全部在父类里面,不同业务的,使用抽象方法,抽取给子类进行实现。抽取过程—抽象方法。
某些特定步骤。
核心:处理某个流程的代码已经都具备,但是其中某个节点的代码暂时不能确定。因此,我们采用模板方法模式,将这个节点的代码实现转移给子类完成。即:处理步骤在父类中定义好,具体的实现延迟到子类中定义。
说白了,就是将一些相同操作的代码,封装成一个算法的骨架。核心的部分留在子类中操作,在父类中只把那些骨架做好。
先执行父类方法,再执行子类方法
//这里使用银行办理业务为例
//首先,定义一个模板。模板中把办理业务用作核心部分,让子类来实现。
public abstract class BankTemplateMethod {
// 1.取号排队
public void takeNumber() {
System.out.println("取号排队。。");
}
// 2.每个子类不同的业务实现,由各自子类实现.
abstract void transact();
// 3.评价
public void evaluate() {
System.out.println("反馈评价..");
}
public void process(){
takeNumber();
transact();
evaluate();
}
}
# 具体模板方法子类
public class DrawMoney extends BankTemplateMethod {
@Override
void transact() {
System.out.println("我要取款");
}
}
// 客户端测试
public class Client {
public static void main(String[] args) {
BankTemplateMethod bankTemplate=new DrawMoney();
bankTemplate.process();
}
}
什么时候使用模板方法
实现一些操作时,整体步骤很固定,但是呢。就是其中一小部分容易变,这时候可以使用模板方法模式,将容易变的部分抽象出来,供子类实现。
开发中应用场景
其实,各个框架中,都有模板方法模式的影子。
数据库访问的封装、Junit单元测试、servlet中关于doGet/doPost方法的调用
Hibernate中模板程序、spring中JDBCTemplate,HibernateTemplate等等
适配器模式
在设计模式中,适配器模式(英语:adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
适配器分类
适配器分为,类适配器、对象适配、接口适配方式
类适配器方式采用继承方式,对象适配方式使用构造函数传递
案列
我们就拿日本电饭煲的例子进行说明,日本电饭煲电源接口标准是110V电压,而中国标准电压接口是220V,所以要想在中国用日本电饭煲,需要一个电源转换器。
//日本110V 电源接口
public interface JP110VInterface {
public void connect();
}
// 日本电源接口实现
public class JP110VInterfaceImpl implements JP110VInterface {
@Override
public void connect() {
System.out.println("日本110V,接通电源,开始工作..");
}
}
// 定义中国220v 电源接口
public interface CN220VInterface {
public void connect();
}
// 实现
public class CN220VInterfaceImpl implements CN220VInterface {
@Override
public void connect() {
System.out.println("中国220V,接通电源,开始工作");
}
}
// 定义日本电饭煲
public class ElectricCooker {
private JP110VInterface jp110VInterface;//日本电饭煲
ElectricCooker(JP110VInterface jp110VInterface){
this.jp110VInterface=jp110VInterface;
}
public void cook(){
jp110VInterface.connect();
System.out.println("开始做饭了..");
}
}
// 定义电源适配器
public class PowerAdaptor implements JP110VInterface {
private CN220VInterface cn220VInterface;
public PowerAdaptor(CN220VInterface cn220VInterface) {
this.cn220VInterface = cn220VInterface;
}
@Override
public void connect() {
cn220VInterface.connect();
}
}
// 测试运行
public class AdaptorTest {
public static void main(String[] args) {
CN220VInterface cn220VInterface = new CN220VInterfaceImpl();
PowerAdaptor powerAdaptor = new PowerAdaptor(cn220VInterface);
// 电饭煲
ElectricCooker cooker = new ElectricCooker(powerAdaptor);
cooker.cook();//使用了适配器,在220V的环境可以工作了。
}
}