zoukankan      html  css  js  c++  java
  • 适配器模式

    适配器模式主要是为了在不能改变现有类的情况下,将一个类转换成另一种类,让他可以适应一个通用的接口

    public interface Printable {
        void printSth();
    }
    
    public class Printer implements Printable {
        @Override
        public void printSth() {
            System.out.println("I can print text");
        }
    }
    
    public class Photogragher {
        public void printPhoto(){
            System.out.println("I can print photogragh");
        }
    }
    
    public class PhotogragherAdapter implements Printable {
        private Photogragher p = null;
        
        public PhotogragherAdapter(Photogragher p) {
            this.p = p;
        }
        
        @Override
        public void printSth() {
            p.printPhoto();
        }
    }
    
    public class Client {
        public static void test(Printable p) {
            p.printSth();
        }
        
        public static void main(String[] args) {
            Printable printer = new Printer();
            Photogragher photogragher = new Photogragher();
            PhotogragherAdapter adapter = new PhotogragherAdapter(photogragher);
            test(printer);
            test(adapter);
        }
    }

    此处的目的就是在不修改Photogragher类的前提下让Photographer也能适用于 Clinet.test() 方法

  • 相关阅读:
    C# 日期帮助类【原创】
    C# 发送邮件
    每日一题力扣453
    每日力扣628
    每日一题力扣41巨坑
    每日一题力扣274
    每日一题力扣442有坑
    每日一题力扣495
    每日一题力扣645
    每日一题力扣697
  • 原文地址:https://www.cnblogs.com/zemliu/p/2752132.html
Copyright © 2011-2022 走看看