The Adapter Pattern(适配器模式)

  • 结构型设计模式的主要目的是将不同的类和对象组合在一起,形成更大或者更复杂的结构体.
  • 适配器的作用就是让不同的复杂的结构体能够更好的对接

 

举例:

现在在有一个画椭圆的函数

 有一个问题就是,这种接口不具备通用性,客户一单改变了画椭圆的需求,就要重新在写一个适配器进行适配.我们的想法是一个适配器就能解决一类问题.

解决方案:

 举例:

	public class Adaptee {//原接口
		public void operation1() {
			System.out.print("This is an existing method.");
			
		}

	}
	
	public interface Target {//新接口,声明所有的方法
		void operation1();
		void operation2();
		
	}
	
	//适配器类
	public class Adapter extends Adaptee implements Target {
		public void operation2() {
			//实现
		}
		
	}
	
	//客户类
	public class Client {
		private static Target adp;
		
		public static void main(String[] args) {
			adp = new Adapter();
			adp.operation1();
			adp.operation2();
			
		}
	}

 有个问题:

再加一个类呢?

 在c++中是允许多继承的,但在java中多继承是不允许的.

新的办法:

 

	public class Adaptee {
		public void operation1() {
			System.out.println("operation 1 is in Adaptee.");
			
		}
		
	}
	
	public interface Target {
		void operation1();
		void operation2();
		
	}
	
	public class Adapter implements Target {
		private Adaptee adaptee;
		
		public Adapter(Adaptee adaptee) {
			this.adaptee = adaptee;
			
		}
		
		public void operation1() {
			adaptee.operation1();
		}
		
		public void operation2() {
			System.out.print("you need to write code for operation2().");
		}
	}

哪些情况下使用适配器模式

  • 你想使用一个存在的类,但是该类的接口不是你想要的.
  • 你想创建一个可复用的类, 该类与一些不相关的接口不相容的类进行合作或者你要改变许多子类的接口.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值