外观模式*
提供了统一的接口,用了访问子系统中的一群接口 定义了一个高层接口,让子系统更容易使用
使用场景:子系统越来越复杂,增加外观模式提供简单调用的接口 构建多层系统结构,利用外观模式作为每层的入口
优点:简化了调用过程,无需了解子系统,防止带来风险 减少系统依赖,松散耦合 更好的划分访问层次 符合迪米特法则 缺点:增加子系统,扩展子系统行为容易引入风险
调用层不需要知道其他类(子系统)做了什么只需要调用给提供的外观者调用接口就可以
public class AppearanceMode {public static void main(String[] args) {PointGift pointGift = new PointGift("书");GiftExchangeService giftExchangeService = new GiftExchangeService();giftExchangeService.giftExchange(pointGift);}}//礼物实体类class PointGift {private String name;public PointGift(String name) {this.name = name;}@Overridepublic String toString() {return "PointGift{" +"name='" + name + '\'' +'}';}}//=====子系统====//校验礼物系统class QualifyService {public boolean isAvailable(PointGift pointGift) {System.out.println("校验" + pointGift + "积分资格通过");return true;}}//支付子系统class PointsPaymentService {public boolean pay(PointGift pointGift) {System.out.println(pointGift + "支付成功");return true;}}//物流子系统class ShippingService {public String shipGift(PointGift pointGift) {System.out.println(pointGift + "进入物流系统");return UUID.randomUUID().toString();}}//外观者提供接口class GiftExchangeService {private QualifyService qualifyService = new QualifyService();private PointsPaymentService pointsPaymentService = new PointsPaymentService();private ShippingService shippingService = new ShippingService();public void giftExchange(PointGift pointGift){if (qualifyService.isAvailable(pointGift)){if (pointsPaymentService.pay(pointGift)){String s = shippingService.shipGift(pointGift);System.out.println("订单号为:"+s);}}}}
SpringJDBC中使用的外观者模式
JDBCUtils.java类
Mybatis中使用的外观者模式
Configuration.java类
装饰者模式*
在不改变原有对象的基础之上,将功能附加在对象上 提供了比继承更有弹性的替代方案
使用场景:扩展一个类的功能或给一个类添加附加职责 动态的给类添加功能,这些功能还可以动态撤销
优点:比继承灵活,不改变原对象的情况下给一个对象扩展功能 缺点:会出现更多代码和更多类 动态装饰时,对层装饰时会更加复杂
对实现类进行装饰
public class DecoratorMode {public static void main(String[] args) {IBattercake iBattercake = new Battercake();IBattercake iBattercake1 = new EggDecorator(iBattercake);System.out.println(iBattercake1.getDesc());IBattercake iBattercake2 = new SausageDecorator(iBattercake1);System.out.println(iBattercake2.getDesc());}}interface IBattercake {String getDesc();int cost();}class Battercake implements IBattercake {@Overridepublic String getDesc() {return "煎饼";}@Overridepublic int cost() {return 8;}}//装饰者模式class Decorator implements IBattercake{IBattercake iBattercake;public Decorator(IBattercake iBattercake) {this.iBattercake = iBattercake;}@Overridepublic String getDesc() {return iBattercake.getDesc();}@Overridepublic int cost() {return iBattercake.cost();}}//装饰者模式的扩展class EggDecorator extends Decorator{public EggDecorator(IBattercake iBattercake) {super(iBattercake);}@Overridepublic String getDesc() {return super.getDesc()+"加鸡蛋";}@Overridepublic int cost() {return super.cost()+1;}}class SausageDecorator extends Decorator{public SausageDecorator(IBattercake iBattercake) {super(iBattercake);}@Overridepublic String getDesc() {return super.getDesc()+"加香肠";}@Overridepublic int cost() {return super.cost()+2;}}
JDK中使用的装饰者模式
BufferReader
Spring-session中使用的装饰者模式
SessionRepositoryRequestWrapper
Mybatis中使用的装饰者模式
FifoCache,LruCache等多个缓存类
适配器模式*
将一个类的接口转换成客户期望的另一个接口 使原本接口不兼容的类可以一起工作
使用场景:已经存在的类,它的方法和需求不匹配时(功能类似,而接口不同)
优点:提高类的透明性和复用,现有的类复用但不需要改变 缺点:可能会增加系统复杂度,增加代码可读的难点
类适配器
通过继承提供功能的类,实现需要返回类型的接口
public class ClassAdapterMode {
public static void main(String[] args) {
IBigCard iBigCard = new ClassAdapterCard();
iBigCard.bigRead();
}
}
//大的读卡器
interface IBigCard{
void bigRead();
}
//小的读卡器
interface ISmallCard{
void smallRead();
}
class BigCard implements IBigCard{
@Override
public void bigRead() {
System.out.println("我是大的读卡器");
}
}
class SmallCard implements ISmallCard{
@Override
public void smallRead() {
System.out.println("我是小的读卡器");
}
}
//类适配器 使大的读卡器有小读卡器的功能
class ClassAdapterCard extends SmallCard implements IBigCard{
@Override
public void bigRead() {
super.smallRead(); //使用小读卡器的方法
}
}
对象适配器
在适配器类中实现提供功能的对象,实现需要返回类型的接口
public class ObjectAdapterMode {
public static void main(String[] args) {
IBigCard adapterCard = new ObjectAdapterCard();
adapterCard.bigRead();
}
}
//大的读卡器
interface IBigCard{
void bigRead();
}
//小的读卡器
interface ISmallCard{
void smallRead();
}
class BigCard implements IBigCard{
@Override
public void bigRead() {
System.out.println("我是大的读卡器");
}
}
class SmallCard implements ISmallCard{
@Override
public void smallRead() {
System.out.println("我是小的读卡器");
}
}
//对象适配器 使大的读卡器有小读卡器的功能
class ObjectAdapterCard implements IBigCard{
ISmallCard iSmallCard = new SmallCard();
@Override
public void bigRead() {
iSmallCard.smallRead(); //使用小读卡器的方法
}
}
JDK中使用的适配器模式
XMLAdapter MethodBeforAdviceAdapter
SpringJPA中使用的适配器模式
JpaVendorAdapter
SpringMVC中使用的适配器模式
HandlerAdapter—DispatchServlet SimpleControllerHandlerAdapter
享元模式*
提供了减少对象数量从而改善应用所需的对象结构方式
适用场景:常常应用于系统底层开发,以便解决系统的性能问题 系统有大量相似对象、需要缓冲池的场景
优点:减少对象的创建,降低内存中对象的数量 减少内存之外的其他资源的占用 缺点:如果是用HashMap可能有线程安全问题 使系统、程序逻辑复杂化
相同对象获取的时候都是获取一个
public class SharingElementMode {
public static void main(String[] args) {
Library library = new Library();
ConcreteBook java = library.lend("java");
System.out.println( java.getName());
}
}
//书类
class ConcreteBook {
private String name;
public ConcreteBook(String name){
this.name = name;
}
public String getName(){
return name;
}
}
//享元模式的实现 --从图书馆借书
class Library {
//用集合容器存储创建好的书
private HashMap<String,ConcreteBook> hashMap = new HashMap<>();
//这就是享元模式 就是相同对象的都是从容器中取 如果没有在进行创建
public ConcreteBook lend(String bookName) {
ConcreteBook concreteBook = null;
if (hashMap.containsKey(bookName)){
concreteBook = hashMap.get(bookName);
}else {
concreteBook = new ConcreteBook(bookName);
hashMap.put(bookName,concreteBook);
}
return concreteBook;
}
}
JDK中使用的享元模式
Integer public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
组合模式
将对象组合成树形结构以表示“部分整体”的层次结构
使用场景:处理一个树形结构时
优点:可以清楚的定义分层次的复杂对象 ,表示对象的全部或部分层次 缺点:限制类型时比较复杂 使设计变得更加抽象
把相同级别的对象放到一个List集合中
public class CombinationMode {
public static void main(String[] args) {
Company company = new ConCreteCompany("总公司","1");
ConCreteCompany conCreteCompany = new ConCreteCompany("子公司", "2");
company.add(conCreteCompany);
conCreteCompany.add(new ConCreteCompany("子子公司","3"));
company.add(new ConCreteCompany("子公司","2"));
company.add(new ConCreteCompany("子公司","2"));
company.display();
}
}
//定义公司的规则
abstract class Company {
//名字
String name;
//级别
String level;
public Company(String address, String name) {
this.name = address;
this.level = name;
}
public abstract void add(Company c);
public abstract void remove(Company c);
public abstract void display();
}
//组合模式的使用--不需要做其他操作下属公司放入集合中
class ConCreteCompany extends Company {
ArrayList<Company> children = new ArrayList<>();
public ConCreteCompany(String address, String name) {
super(address, name);
}
@Override
public void add(Company c) {
children.add(c);
}
@Override
public void remove(Company c) {
children.remove(c);
}
//查看当前公司及下属公司
@Override
public void display() {
System.out.println(name+"---"+level);
for (Company c:children){
c.display();
}
}
}
JDK中使用的组合模式
HashMap—>putAll方法 ArrayList->addAll方法
Mybatis中使用的组合模式
SqlNode的实现类
桥接模式*
可以将一个大类或者一系列紧密相关的类拆分为抽象和实现两个独立的层次
使用场景:抽象和具体实现直接增加更多灵活性 一个类存在两个或多个独立变化的维度,且这两个或多个维度都需要独立扩展
优点:分离抽象部分及其具体实现部分 提供了可扩展性 缺点:增加了理解和设计难点 需要正确的识别出系统中两个独立变化的维度
将两个类关联起来
public class BridgingMode {
public static void main(String[] args) {
Account liveAccount = new LiveAccount();
Account deadAccount = new DeadAccount();
Bank abcBank = new ABCBank(liveAccount);
Account account = abcBank.openAccount();
account.showAccountType();
Bank icbcBack = new ICBCBank(deadAccount);
Account account1 = icbcBack.openAccount();
account1.showAccountType();
}
}
//账户接口
interface Account {
Account openAccount();
void showAccountType();
}
class LiveAccount implements Account {
@Override
public Account openAccount() {
return new LiveAccount();
}
@Override
public void showAccountType() {
System.out.println("查看活期账户");
}
}
class DeadAccount implements Account {
@Override
public Account openAccount() {
return new DeadAccount();
}
@Override
public void showAccountType() {
System.out.println("查看死期账户");
}
}
//银行抽象类
abstract class Bank {
protected Account account;
public Bank(Account account) {
this.account = account;
}
abstract Account openAccount();
}
class ABCBank extends Bank {
public ABCBank(Account account) {
super(account);
}
@Override
Account openAccount() {
System.out.println("打开了农业银行账户");
account.openAccount();//进行打开银行账户的操作
return account ;
}
}
class ICBCBank extends Bank {
public ICBCBank(Account account) {
super(account);
}
@Override
Account openAccount() {
System.out.println("打开了工商银行账户");
account.openAccount();//进行打开银行账户的操作
return account ;
}
}
JDK中使用的桥接模式
Driver的实现类和DirverManager形成桥接模式
代理模式*
一个类代表另一个类的功能
使用场景:保护目标对象 增强目标对象
优点:将代理对象和真是被调用的目标对象分离 一定程度上降低了系统的耦合度。扩展性好 缺点:造成系统设计中类的数目增加 造成请求处理速度变慢
静态代理
对返回对象执行做一些特殊处理
public class StaticProxyPattern {
public static void main(String[] args) {
Store store = new ProxyStore();
Iphone iphone = store.sellPhone();
}
}
//手机
class Iphone {
private String name;
private String color;
}
//手机的商店的接口
interface Store {
Iphone sellPhone();
}
//手机生产工厂
class AppleStore implements Store {
//生产手机
public Iphone productPhone() {
Iphone iphone = new Iphone();
return iphone;
}
@Override
public Iphone sellPhone() {
Iphone iphone = this.productPhone();
return iphone;
}
}
//代理商店--可以在卖的时候进行一些其他的操作
class ProxyStore implements Store {
private AppleStore store = new AppleStore();
@Override
public Iphone sellPhone() {
//得到手机后可以进行其他操作
Iphone iphone = this.store.productPhone();
System.out.println("我要进行加价了");
return iphone;
}
}
动态代理
只能代理接口
public class DynamicAgentMode {
public static void main(String[] args) {
Store store = StoreProxy.getStore(AppleStore.class);
Iphone iphone = store.sellPhone();
iphone.play();
}
}
//手机
class Iphone {
String name;
String color;
public void play() {
System.out.println("玩手机");
}
}
//手机的商店的接口
interface Store {
Iphone sellPhone();
}
//要被代理的对象 因为是动态代理不需要在这里面做事情 所以可以是接口
interface AppleStore extends Store {
Iphone sellPhone();
}
//动态代理
class StoreProxy {
public static <T> T getStore(Class clazz) {
ClassLoader classLoader = clazz.getClassLoader();
Class[] clazzs = {clazz};
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName());
//参数1 代理对象 参数2 代理的方法 参数3 代理执行时传递的参数
Class declaringClass = method.getDeclaringClass();
System.out.println(declaringClass);//AppleStore
//根据不同的判断返回不同的class
if (declaringClass == AppleStore.class) {
//可以返回对象之前做处理
return new Iphone();
}
return null;
}
};
/*
参数1:ClassLoader
参数2:Class数组
参数3:InvocationHandler
*/
T proxy = (T) Proxy.newProxyInstance(classLoader, clazzs, invocationHandler);
return proxy;
}
}
Spring中使用的代理模式
Spring—ProxyFactoryBean
Mybatis中使用的代理模式
Mybatis—>MapperProxyFactory.newInstance
