码迷,mamicode.com
首页 > 其他好文 > 详细

Adapter Pattern

时间:2017-03-11 11:31:44      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:source   pre   init   abstract   style   nbsp   ring   .so   new   

Introduction:you have a class with some functions which are not exactly what you can use directerly to sovle the problem you face with.so some adaption is needed to help you reuse the old class without any modification but you can also add some new functions to solve the fatal problem. In a word,we could build a new class with the old one.

example: 

You wanna to say "Hello world",before that you tend to do something else and clear the initialization after the class object died.

So what you have is:

class YouHave{
public void hello(){
System.out.print("Hello ");
}
public void world(){
System.out.println("world.");
}
}

Waht You wanna is:

Do something of initialization.
Hello world.
Do something to release the source.

 

We can use a interface to transit:

abstract class YouWanna{
abstract public void wanna();
}

Then build a new class(called adapter):

class Surrogate extends YouWanna{
private YouHave have;
public Surrogate(YouHave have){
this.have=have;
}
public void wanna(){
System.out.println("Do something of initialization.");
have.hello();
have.world();
System.out.println("Do something to release the source.");
}
}

Now you can use it:

public class AdapterPattern {
public static void main(String[] args) {
YouHave have=new YouHave();
Surrogate surrogate=new Surrogate(have);
surrogate.wanna();
}
}

The Adapter parttern is often confused with Proxy parttern ,but when we use an adapter,
we do not to keep the same interface as using the proxy one.
The end.

Adapter Pattern

标签:source   pre   init   abstract   style   nbsp   ring   .so   new   

原文地址:http://www.cnblogs.com/ssMellon/p/6534275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!