zoukankan      html  css  js  c++  java
  • Java中的23种设计模式之——适配器Adapter模式(2)

     一、什么是适配器模式?

    适配器模式,属于结构型模式,其主要作用是将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

    /**
     * 适配器(Adapter)模式---结构型
     * 
     * @author ouyanxia
     * DutchAddress类通过适配器调用Address类中的方法
     */
    public class Adapter {
        public static void main(String[] args) {
            Address addr = new Address();
            DutchAddressAdapter addrAdapter = new DutchAddressAdapter(addr);
            System.out.println("
     The DutchAdapter
    ");
            testDutch(addrAdapter);
        }
        static void testDutch(DutchAddress addr){
            addr.straat();
            addr.postcode();
            addr.plaats();
        }
    }
    
    class Address {
        public void street() {
            System.out.println("Address.street()");
            // 实现代码忽略
        }
    
        public void zip() {
            System.out.println("Address.zip()");
            // 实现代码忽略
        }
    
        public void city() {
            System.out.println("Address.city()");
            // 实现代码忽略
        }
    }
    
    class DutchAddress {
        public void straat() {
            // 实现代码忽略
        }
    
        public void postcode() {
            // 实现代码忽略
        }
    
        public void plaats() {
            // 实现代码忽略
        }
    }
    //对象适配器
    class DutchAddressAdapter extends DutchAddress{
        private Address address;
        public DutchAddressAdapter(Address addr){
            address = addr;
        }
        @Override
        public void straat() {
            address.street();
        }
        @Override
        public void postcode() {
            address.zip();
        }
        @Override
        public void plaats() {
            address.city();
        }
    }

    运行结果

     The DutchAdapter
    
    Address.street()
    Address.zip()
    Address.city()
  • 相关阅读:
    POJ 2752 Seek the Name, Seek the Fame
    POJ 2406 Power Strings
    KMP 算法总结
    SGU 275 To xor or not to xor
    hihocoder 1196 高斯消元.二
    hihoCoder 1195 高斯消元.一
    UvaLive 5026 Building Roads
    HDU 2196 computer
    Notions of Flow Networks and Flows
    C/C++代码中的笔误
  • 原文地址:https://www.cnblogs.com/ouyanxia/p/8360241.html
Copyright © 2011-2022 走看看