Java中23种设计模式详解:七大结构型模式的详细分析

210 阅读8分钟

这是我参与更文挑战的第17天,活动详情查看:更文挑战

结构型模式

适配器模式(Adapter Pattern)

  • 对象的适配器模式是各种结构型模式的起源 在这里插入图片描述
  • 适配器模式: 将某个类的接口转换成客户端期望的另一个接口表示
  • 目的: 消除由于接口不匹配所造成的类的兼容性问题
  • 适配器模式主要分为三类:
    • 类的适配器模式
    • 对象的适配器模式
    • 接口的适配器模式
类的适配器模式

在这里插入图片描述

  • 核心思想: 有一个Source类,拥有一个方法待适配,目标接口是Targetable, 通过Adapter类,将Source的功能扩展到Targetable
- Source
public class Source{
	public void method1(){
		System.out.println("This is original method!");
	}
} 

- Targetable
public interface Targetable{
	/* 与原类中的方法相同 */
	public void method1();

	/* 新类方法 */
	public void method2();
}

- Adapter
public class Adapter extends Source implemments Targetable{
	@Override
	public void method2(){
		System.out.println("This is the targetable method!");
	}
}
  • Adapter类继承Source类,实现Targetable接口:
- AdapterTest
public class AdapterTest{
	public static void main(String[] args){
		Targetable target=new Adapter();
		target.method1();
		target.method2();
	}
}
  • 这样Targetable接口的实现类就具有Source类的功能
对象的适配器模式
  • 基本思路和类的适配器相同,只是将Adapter类作修改 ,不继承Source类,而是持有Source类的实例,以达到解决兼容性问题 在这里插入图片描述
- Wrapper
public class Wrapper implements Targetable{
	private Source source;

	public Wrapper(Source source){
		super();
		this.source=source;
	}

	@Override
	public void method1(){
		source.method1();
	}

	@override
	public void method2(){
		System.out.println("This is the targetable method!");
	}
}




- Test
public class AdapterTest{
	public static void main(String[] args){
		Source source=new Source();
		Targetable target=new Wrapper(source);
		target.method1();
		target.nethod2();
	}
}
接口的适配器模式
  • 一个接口中有多个抽象方法,当写该接口的实现类时,必须实现该接口的所有方法,这样明显比较浪费,因为并不是所有的方法都是需要用到的,有时只要引入一些即可.为了解决这样的问题,引入了接口适配器模式
  • 接口适配器模式: 借助于一个抽象类,该抽象类实现了该接口以及所有的方法,只需要和该抽象类进行联系即可.
  • 只需要写一个类,继承该抽象类,重写需要用到的方法 在这里插入图片描述
- Sourceable
public interface Sourceable{
	public void method1();
	public void method2();
}




- Wrapper-抽象类
public abstract class Wrapper implements Sourceable{
	public void method1(){}

	public void method2(){}
}




- SourceSub1
public class SourceSub1 extends Wrapper{
	public void method1(){
		System.out.println("The sourceable interface's first Sub");
	}
}




- SourceSub2
public class SourceSub2 extends Wrapper(){
	public void method2(){
		System.out.println("The Sourceable interface's second Sub");
	}
}




- WrapperTest
public class WrapperTest{
	public static void main(String[] args){
		Sourceable source1=new SourceSub1();
		Sourceable source2=new SourceSub2();

		source1.method1();
		source1.method2();
		source2.method1();
		source2.method2();
	}
}
  • 三种适配器模式的应用场景:
    • 类的适配器模式:
      • 当希望一个类转换成满足另一个新接口的类时,可以使用类的适配器模式
      • 创建一个新类,继承原有的类,实现新的接口即可
    • 对象的适配器模式:
      • 当希望一个对象转换成满足另一个新接口的对象时,可以使用对象的适配器模式
      • 创建一个Wrapper类,持有原类的一个实例,在Wrapper类的方法中,调用实例的方法即可
    • 接口的适配器模式:
      • 当不希望实现一个接口中所有的方法时,可以使用接口的适配器模式
      • 创建一个抽象类Wrapper,实现所有方法,写其它类时,只要继承抽象类即可

装饰器模式(Decorator)

  • 装饰器模式: 给一个对象动态地增加一些新的功能
  • 装饰器模式要求装饰对象和被装饰对象实现同一个接口, 装饰对象持有被装饰对象的实例 在这里插入图片描述
  • Source类时被装饰类 ,Decorator类是装饰类,可以为Source类动态地增加一些功能:
- Sourceable
public interface Sourceable{
	public void method();
}




- Source
public class Source implements Sourceable{
	@Override
	public void method(){
		System.out.println("The original method!");
	}
}




- Decorator
public class Decorator implements Sourceable{
	private Sourceable source;
	public Decorator(Sourceable source){
		super();
		this.source=source;
	}

	@Override
	public void method(){
		System.out.println("Before decorator!");
		source.method();
		System.out.println("After decorator!");
	}
}




-Test
public class DecoratorTest{
	public static void main(String[] args){
		Sourceable source=new Source();
		Sourceable obj=new Decorator(source);
		obj.method();
	}
}
  • 装饰器模式应用场景:
    • 需要扩展一个类的功能
    • 动态地为一个对象增加功能,而且还能动态地撤销(继承的功能是静态的,不能动态增删)
  • 装饰器模式的缺点: 产生过多类似的对象,不易排错

代理模式(Proxy)

  • 代理模式: 创建一个代理类,替原对象进行一些操作 在这里插入图片描述
- Sourceable
public interface Sourceable{
	public void method();
}




- Source
public class Source implements Sourceable{
	@Override
	public void method(){
		System.out.println("The original method!");
	}
}




- Proxy
public class Proxy implements Sourceable{
	private Source source;
	public Proxy(){
		super();
		this.source=new Source;
	}

	@Override
	public void method(){
		before();
		source.method();
		after();
	}

	public void before(){
		System.out.println("Before Proxy!");	
	}
	
	public void after(){
		System.out.println("After Proxy!");
	}	
}




- ProxyTest
public class ProxyTest{
	public static void main(String[] args){
		Sourceable source=new Proxy();
		source.method();
	}
}
  • 代理模式的应用场景:
    • 已有的方法在使用的时候需要对原有的方法进行改进,有两种方法:
      • 修改原有的方法来适应: 这样违反了"对扩展开放,对修改关闭"的原则 .不推荐使用
      • 采用一个代理类调用原有的方法,且对产生的结果进行控制. 即代理模式
  • 使用代理模式,可以将功能划分的更加清晰,有助于后期维护

外观模式(Facade)

  • 在Spring中,可以将类与类之间的关系配置到配置文件中
  • 外观模式: 为了解决类与类之间的依赖关系,将类鱼雷之间的关系放到一个Facade类中,降低类与类之间的耦合度,该模式中没有涉及到接口 在这里插入图片描述
- CPU
public class CPU{
	public void startup(){
		System.out.println("CPU startup!");
	}

	public void shutdown(){
		System.out.println("CPU shutdown!");
	}
}




- Memory
public class Memory{
	public void startup(){
		System.out.println("Memory startup!");
	}

	public void shutdown(){
		System.out.println("Memory shutdown!");
	}
}




- Disk
public class Disk{
	public void startup(){
		System.out.println("Disk startup!");
	}

	public void shutdown(){
		System.out.println("Disk shutdown!");
	}
}




- Computer
public class Computer{
	private CPU cpu;
	private Memory memory;
	private Disk disk;

	public Computer(){
		cpu=new CPU();
		memory=new Memory();
		disk=new Disk();
	}

	public void startup(){
		System.out.println("Start the computer!");
		cpu.startup();
		memory.startup();
		disk.startup();
		System.out.println("Start the computer finished!");
	}

	public void shutdown(){
		System.out.println("Begin to close the computer!");
		cpu.shutdown();
		memory.shutdown();
		disk.shutdown();
		System.out.println("Computer closed!");
	}
}




-User
public class User{
	public static void main(String[] args){
		Computer computer=new Computer();
		computer.startup();
		computer.shutdown();
	}
}
  • 如果没有Computer,CPU,Memory,Disk之间会互相持有实例,产生关系,这样会造成严重依赖
  • 修改一个类,可能会带来其它类的修改
  • 有了Computer类,各个类之间的关系就放在类Computer类里,这样就起到解耦的作用

桥接模式(Bridge)

  • 桥接模式: 将事物和具体实现分开,二者可以各自独立的变化
  • 将抽象化与实现化解耦,使得二者可以独立变化:
    • JDBC桥DriverManager:
      • JDBC连接数据库的时候,在各个数据库之间进行切换,基本不需要改动太多的代码,甚至一点不用改动
      • 原因在于JDBC提供统一接口,每个数据库提供各自实现,用一个叫作数据库驱动的程序来桥接即可 在这里插入图片描述
- Sourceable
public interface Sourceable{
	public void method();
}




- SourceSub1
public class SourceSub1 implements Sourceable{
	@Override
	public void method(){
		System.out.println("This is the first sub!");
	}
}




- SourceSub2
public class SourceSub2 implements Sourceable{
	@Override
	public void method(){
		System.out.println("This is the second sub!");
	}
}




- 定义一个桥,持有Sourceable的一个实例
public abstract class Bridge{
	private Sourceable source;

	public void method(){
		source.method();
	}

	public Sourceable getSource(){
		return source;
	}

	public void getSource(Sourceable source){
		this.source=source;
	}
}




- MyBridge
public class MyBridge extends Bridge{
	public void method(){
		getSource().method();
	}
}




- BridgeTest
public class BridgeTest{
	public static void main(String[] args){
		Bridge bridge=new MyBridge();

		/* 调用第一个对象 */
		Sourceable source1=new SourceSub1();
		bridge.setSource(source1);
		bridge.method();

		/* 调用第二个对象 */
		Sourceable source2=new SourceSub2();
		bridge.setSource(source2);
		bridge.method();
	}
}
  • 通过对Bridge类的调用,实现了对接口Sourceable的实现类SourceSub1和SourceSub2的调用
  • 示例: JDBC连接原理 在这里插入图片描述

组合模式(Composite)

  • 组合模式: 部分-整体模式,在处理类似树形结构的问题时比较方便 在这里插入图片描述
- TreeNode
public class TreeNode{
	private String name;
	private TreeNode parent;
	private Vector<TreeNode> children=new Vector<TreeNode>();

	public TreeNode(String name){
		this.name=name;
	}

	public String getName(){
		return name;
	}

	public void setName(String name){
		this.name=name;
	}

	public TreeNode getParent(){
		return parent;
	}

	public void setParent(TreeNode parent){
		this.parent=parent;
	}

	/* 添加孩子节点 */
	public void add(TreeNode node){
		children.add(node);
	}

	/* 删除孩子节点 */
	public void remove(TreeNode node){
		children.remove(node);
	}

	/* 获得孩子节点 */
	public Enumeration<TreeNode> getChildren(){
		return children.elements();
	}
}




- Tree
public class Tree{
	TreeNode root=null;

	public Tree(String name){
		root=new TreeNode(name);
	}

	public void main(String[] args){
		Tree tree=new Tree("A");
		TreeNode nodeB=new TreeNode("B");
		TreeNode nodeC=new TreeNode("C");

		nodeB.add(nodeC);
		tree.root.add(nodeB);
		System.out.println("Build the tree finished!");
	}
}
  • 组合模式使用场景:
    • 将多个对象组合在一起进行操作
    • 常用于表示树形结构中:二叉树

享元模式

  • 享元模式: 主要目的是实现对象共享,即共享池
  • 当系统中对象多的时候可以减少内存的开销,通常与工厂模式一起使用 在这里插入图片描述
  • FlyWeightFactory: 负责创建和管理享元单元
    • 当一个客户端请求时,工厂需要检查当前对象池中是否有符合条件的对象
    • 如果有,就返回已经存在的对象
    • 如果没有,就创建一个新对象
  • FlyWeight: 超类
  • 共享的对象的特点:
    • 共享对象有一些共同的属性
    • 这些属性对于每个连接来说都是一样的
  • 基于共享对象的特点,可以用享元模式处理共享对象:
    • 将类似属性作为内部数据
    • 其它的属性作为外部数据
    • 在方法调用时,当作参数传进来
  • 这样可以节省内存空间,减少实例的数量
  • 示例: 数据库连接池 在这里插入图片描述
public class ConnectionPool{
   private Vector<Connection> pool;

   /* 公有属性 */
   private String url="jdbc:mysql://localhost:3306/test";
   private String username="root";
   private String password="root";
   private String driverClassName="com.mysql.jdbc.Driver";
   private int poolSize=100;
   private static ConnectionPool instance=null;
   Connection conn=null;

   /* 构造方法,负责初始化 */
   private ConnectionPool(){
   	pool = new Vector<Connection>(poolSize);
   	
   	for(int i=0;i<poolSize;i++){
   		try{
   			Class.forName(driverClassName);
   			conn=DriverManager.getConnection(url,user,password);
   			pool.add(conn);
   	}catch(ClassNotFoundException e){
   			e.printStackTrace();
   	}catch(SQLEXception e){
   			e.printStackTrace();
   	}
   }	
}

   /* 返回连接到连接池 */
   public sysnchronized void release(){
   		pool.add(conn);
   }

   /* 返回连接池中的一个数据库 */
   public syschronized Connection getConnection(){
   		if(pool.size()>0){
   			Connection conn=pool.get(0);
   			pool.remove(conn);
   			return conn;
   		}else{
   			return null;
   		}
   }
}
  • 通过连接池的连接,实现数据库连接的共享:
    • 不需要每一次重新创建连接,节省数据库重新创建的开销,提升了系统系能