共计 2109 个字符,预计需要花费 6 分钟才能阅读完成。
心愿客官开心的观看
前言
后面介绍了三种 工厂模式
, 面试除了工厂模式之外还有其余的模式会问, 本次我将说说 适配器模式
, 装璜模式
, 还是老规矩, 放在 一个.java 外面
, 复制即可食用
适配器模式
适配器模式分为 类适配器
和对象适配器
。类适配器比拟间接,继承待适配类,实现目标接口,使得待适配类满足指标接口的特定性能。直白一点说须要加接口Traget
, 在接口中调用Adaptee
中的办法. 这样就能够实现新的 扩大
.
上面是类适配器
流程图:
测试表代码
package sample; | |
// 类适配器 demo | |
public class AdapteeClassDemo { | |
interface Target{public void request() ; | |
} | |
static class Adaptee {public void requestAdaptee() {System.out.println("system.out.println(adaptee)"); | |
} | |
} | |
static class TargetAdaptee extends Adaptee implements Target{ | |
@Override | |
public void request() { | |
// 处理过程 | |
super.requestAdaptee(); | |
// 处理过程 | |
} | |
} | |
public static void main(String[] args) {Target targetAdaptee = new TargetAdaptee(); | |
targetAdaptee.request();} | |
} | |
后果:
system.out.println(adaptee)
对象适配器
对象适配器与类适配器不同之处在于,类适配器通过继承来实现适配,对象适配器则是通过关联来实现,这里略微批改一下 TargetAdaptee 类即可将转变为对象适配器
流程图:
测试表代码
static class TargetAdaptee implements Target{Adaptee adaptee = new Adaptee(); | |
@Override | |
public void request() { | |
// 处理过程 | |
adaptee.requestAdaptee(); | |
// 处理过程 | |
} | |
} |
装璜模式
装璜模式,顾名思义,就是将某个类从新打扮一下,使得它比原来更“丑陋”,或者在性能上更弱小,这就是装璜器模式所要达到的目标。然而作为原来的这个类的使用者还不应该感触到装璜前与装璜后有什么不同,即用法不变,否则就毁坏了原有类的构造了,所以装璜器模式要做到对被装璜类的使用者通明,这是对装璜器模式的一个根本要求
流程图:
package sample; | |
// 装璜模式 demo | |
public class DecoratorDemo { | |
interface Apple{public void sout() ; | |
} | |
static class Adaptee {public void requestAdaptee() {System.out.println("system.out.println(adaptee)"); | |
} | |
} | |
static class ConcreteApple implements Apple{ | |
@Override | |
public void sout() {System.out.println("system.out.print(apple)"); | |
} | |
} | |
static class Decorator implements Apple{ | |
Apple apple; | |
Decorator(Apple apple){super(); | |
this.apple=apple; | |
} | |
@Override | |
public void sout() {apple.sout(); | |
} | |
} | |
static class ConcreteDecorator extends Decorator{ | |
Apple apple; | |
ConcreteDecorator(Apple apple){super(apple); | |
} | |
@Override | |
public void sout() {System.out.println(); | |
System.out.println("装璜器增加的输入"); | |
System.out.println("system.out.print(Apple)"); | |
System.out.println("装璜器输入完结"); | |
} | |
} | |
public static void main(String[] args) {Apple apple = new ConcreteApple(); | |
apple.sout(); | |
// 装璜模式 | |
Apple decoratorApple = new ConcreteDecorator(apple); | |
decoratorApple.sout();} | |
} | |
后果:
system.out.print(apple) | |
装璜器增加的输入 | |
system.out.print(Apple) | |
装璜器输入完结 |
总结
适配器模式的意义
将一个接口转变成另一个接口,目标是通过扭转接口来达到重复使用的目标。
装璜器模式的意义
不扭转被装璜对象的接口,而是放弃原有的接口,加强原有对象的性能,或扭转原有对象的解决形式而增进步性能。
明天周天, 大家留神劳动, 今天就要下班了
创作不易, 如果本篇文章能帮忙到你, 请给予反对, 赠人玫瑰, 手有余香,虫虫蟹蟹观众姥爷了
正文完