设计模式心得:适配器模式(adapter pattern)和外观模式(facade pattern)

适配器简单来说,就是一个插座转换头,将一套接口转换为另外一套接口。

interface A { void foo1(); void foo2();}
Interface B { void foo1(); void foo3();}

class BImpl implements B {
	//Do something to implement B
}
class BtoAAdapter implements A {
	B b;
	BtoAAdapter(B b) {
		this.b = b;
	}
	@override
	void foo1() { 
		//use B to implement, possibly just call b.foo1(), then modify some random things e.g: 
		b.foo1();
		System.out.println(" Doing random thing ... so that my behavior is just like A.foo1()");
	}
	void foo2() { 
		// use B to implement
		b.foo3();
		//blahblah
	}
}

在这个例子里面,BtoAAdapter用某个实现了B接口的类实现了A接口, 这样我们就可以用BImpl的对象来当A用。测试代码:

BImpl testB = new BImpl();
A mockA = new BtoAAdapter(testB);
mockA.foo1();
mockA.foo2();

有了适配器模式,我们可以在某些情况不需要做很大的refactor。 另外,接受第三方数据以及API,互相有少许的差距怎么办?可以用Adapter。


============分割线============

外观模式: 何为外观(facade)?更精准的建筑学术语叫立面。 简单说来就是建筑展现在外面的一面。 我们看到的正常建筑,不可能会把乱七八糟的管线,或是开关后面的机械暴露在表面的。立在外面的都是干净整洁的墙和窗户,以及几个开关。 这就是facade pattern的核心价值。 把几个类/接口经常一起用的方法整合到一起,做成一个单独的XXXFacade类,用户操作这个类就行了,脏活累活不用用户干。


举个例子, 做一件事情DoSomething1(),需要依次call: A.foo1(), B.foo2,C.foo3() 可以用这个Facade

public DoSomethingFacade {
	A a;
	B b;
	C c;
	public DoSomethingFacade(A a, B b, C c) {
		this.a = a;
		this.b = b;
		this.c = c;
	}
	
	public void DoSomething1() {
		a.foo1();
		b.foo2();
		c.foo3();
	}

	// There could be multiple stuff going here, like:
	public void DoSomething2() { // blabla }
}

有了这个Facade,客户直接call doSomethingFacade.DoSomething1() 就可以了,无需call乱七八糟一堆东西。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值