• java 适配器模式


    适配器:基于现有类所提供的服务,向客户提供接口,以满足客户的期望

                                                           《Java设计模式》

    一、类适配器:

    OtherOperation(已存在所需功能的类):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:39:18
     */
    public class OtherOperation {
        public int add(int a, int b){
            return a + b;
        }
    }

    Operation(为所要实现的功能定义接口):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:40:12
     */
    public interface Operation {
        public int add(int a, int b);
    }

    OperationAdapter(适配器):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:40:41
     * 对象适配器
     */
    public class OperationAdapter extends OtherOperation implements Operation{
    
    
    }

    -----------------------------------------------------------------------------------------------------------------------------------

    二、对象适配器:

    假如客户接口期望的功能不止一个,而是多个。
    由于java是不能实现多继承的,所以我们不能通过构建一个适配器,让他来继承所有原以完成我们的期望,这时候怎么办呢?只能用适配器的另一种实现--对象适配器:
    符合java提倡的编程思想之一,即尽量使用聚合不要使用继承。

    OtherAdd和OtherMinus(已存在功能的两个类):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:50:14
     */
    public class OtherAdd {
        public int add(int a, int b){
            return a + b;
        }
    }
    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:50:46
     */
    public class OtherMinus {
        public int minus(int a, int b){
            return a - b;
        }
    }

    Operation(为所要实现的功能定义接口):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:51:59
     */
    public interface Operation {
        public int add(int a, int b);
        public int minus(int a, int b);
    }

    OperationAdapter(通过适配类的对象来获取):

    /**
     * @author com.tiantian
     * @version 创建时间:2012-11-21 下午4:52:36
     */
    public class OperationAdapter implements Operation{
        private OtherAdd otherAdd;
        private OtherMinus otherMinus;
        
        public OtherAdd getOtherAdd() {
            return otherAdd;
        }
    
        public void setOtherAdd(OtherAdd otherAdd) {
            this.otherAdd = otherAdd;
        }
    
        public OtherMinus getOtherMinus() {
            return otherMinus;
        }
    
        public void setOtherMinus(OtherMinus otherMinus) {
            this.otherMinus = otherMinus;
        }
    
        @Override
        public int add(int a, int b) {
            return otherAdd.add(a, b);
        }
    
        @Override
        public int minus(int a, int b) {
            return otherMinus.minus(a, b);
        }
    
    }
  • 相关阅读:
    sql执行的顺序
    $(obj).index(this) 与 $(this).index()的区别
    java取得百分比
    取得input的特殊值
    清除select的边框和三角形
    在jsp页面中获取列表长度
    mysql mybatis 批量更新和新增
    oracle mybatis 批量更新和新增
    jstl if else 判断
    判断radio,select,checkbox是否选中的方法
  • 原文地址:https://www.cnblogs.com/tiantianbyconan/p/2781050.html
Copyright © 2020-2023  润新知