适配器模式(Adapter)(对象结构型模式)

参考文档:

1.设计模式-可复用面向对象软件的基础

2.http://blog.csdn.net/guolin_blog/article/details/9400141(Java设计模式透析之 —— 适配器(Adapter))


适配器模式(Adapter)(对象结构型模式)

理论方面的知识,请查看参考文档的内容。

看一下adapter的结构:

类适配器,在java中的实现,表现为实现多个接口类,进行匹配:


对象适配器,在java中的实现,表现为对象组合:



代码实现,案例是参考文档2中的,实现的方式是:对象适配器,实现adapter的类:ServerOne.java。

PlayerCount.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public interface PlayerCount {

    String getServerName();

    int getPlayerCount();

}
ServerOne.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public class ServerOne implements PlayerCount {
    @Override
    public String getServerName() {
        return "1服";
    }

    @Override
    public int getPlayerCount() {
        return new ServerFirst().getOnlinePlayerCount();
    }
}
ServerTwo.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public class ServerTwo implements PlayerCount {
    @Override
    public String getServerName() {
        return "2服";
    }

    @Override
    public int getPlayerCount() {
        return Utility.getOnlinePlayerCount(2);
    }
}
ServerThree.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public class ServerThree implements PlayerCount {
    @Override
    public String getServerName() {
        return "3服";
    }

    @Override
    public int getPlayerCount() {
        return Utility.getOnlinePlayerCount(3);
    }
}
Utility.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public class Utility {
    public static int getOnlinePlayerCount(int i) {
        return (int) (Math.random() * 100);
    }
}
ServerFirst.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public class ServerFirst {
    public int getOnlinePlayerCount() {
        return (int) (Math.random() * 100);
    }
}
Client.java:
package com.rick.designpattern.adapter;

/**
 * Created by MyPC on 2017/6/29.
 */
public class Client {


    public static void main(String[] args) {
        ServerOne one = new ServerOne();
        System.out.println(one.getServerName() + "=" + one.getPlayerCount());
        ServerTwo two = new ServerTwo();
        System.out.println(two.getServerName() + "=" + two.getPlayerCount());
        ServerThree three = new ServerThree();
        System.out.println(three.getServerName() + "=" + three.getPlayerCount());
    }
}

阅读更多
文章标签: 设计模式
个人分类: 理解设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭