zoukankan      html  css  js  c++  java
  • Java设计模式——适配器模式

    适配器模式分为两种:类适配器模式和对象适配器模式。废话不多说,直接上代码。

    1、类适配器模式

    public interface TargetInterface {
        void method1();
    
        void method2();
    }
    
    /**
     * 需要被适配的类,该类要实现TargetInterface接口,但是不能被修改。
     *
     */
    class Adaptee {
        public void method1() {
            System.out.println("method1");
        }
    }
    
    /**
     * 适配器类
     *
     */
    class Adapter extends Adaptee implements TargetInterface {
        public void method2() {
            System.out.println("method2");
        }
    }
    
    public class AdapterTest {
        public static void main(String[] args) {
            Adapter adapt = new Adapter();
            adapt.method1();
            adapt.method2();
        }
    }

    2、对象适配器模式

    public interface TargetInterface {
        void method1();
    
        void method2();
    }
    
    /**
     * 需要被适配的类,该类要实现TargetInterface接口,但是不能被修改。
     *
     */
    class Adaptee{
        public void method1(){
            System.out.println("method1");
        }
    }
    
    /**
     * 适配器类
     *
     */
    class Adapter implements TargetInterface {
        private Adaptee adaptee;
    
        public Adapter(Adaptee adaptee) {
            this.adaptee = adaptee;
        }
    
        public void method1() {
            this.adaptee.method1();
        }
    
        public void method2() {
            System.out.println("method2");
        }
    }
    
    public class AdapterTest {
        public static void main(String[] args) {
            Adapter adapt = new Adapter(new Adaptee());
            adapt.method1();
            adapt.method2();
        }
    }
  • 相关阅读:
    第一天站立会议
    Sprint会议计划
    软件需求分析
    团队介绍
    再写行转列和列转行
    二十三种设计模式之:组合(Composite)模式(部分·整体模式)
    对于类和对象的认识
    对排序的认识
    设计模式分类
    二十三种设计模式之:适配器模式
  • 原文地址:https://www.cnblogs.com/zengxiaoliang/p/8074949.html
Copyright © 2011-2022 走看看