zoukankan      html  css  js  c++  java
  • linkin大话设计模式--适配器模式

    linkin大话设计模式--适配器模式


    大家知道,在java中只允许单继承,但是在实际问题中往往都需要多继承,java引入了接口这一概念。(一个类可以实现多个接口)


    由于接口中都是抽象方法,那么我们在实现它的时候就必须全部覆写这些方法。假如我有一个类,这个类只想覆写一部份方法怎么办?

     

    在接口与这个类中间可以加一个抽象类:

    抽象类去覆写接口中的全部方法,而那个类去继承这个抽象类,根据需要覆写抽象类中的方法。(简单的适配器模式)


    代码如下:


     

    public class AbstractTest {
            public static void main(String[] args) {
                Eat p=new MyPerson();
                p.eatBread();
                p.eatApple();
        }
    
    }
    //编译时的接口
    interface Eat{
        public void eatBread();
        public void eatApple();
        public void eatBanana();
    }
    
    //接口和每一个具体的实现类之间的抽象类
    abstract class PersonEat implements Eat{
        public void eatBread(){};
        public void eatApple(){};
        public void eatBanana(){};
    }
    
    //具体的子类实现
    class MyPerson extends PersonEat{
        public void eatBread(){
            System.out.println("我在吃面包...");
        }
        
        public void eatApple(){
            System.out.println("我在吃苹果...");
        }
    }
    



  • 相关阅读:
    浅析TCP /UDP/ IP协议
    大小端模式
    小技巧—计算内存
    浅谈启发式合并
    浅谈换根DP
    POJ 3585 Accumulation Degree
    OSGi类加载问题
    Redis缓存集群方案
    Tair分布式缓存
    Tedis:淘宝的Redis的Java客户端开发包
  • 原文地址:https://www.cnblogs.com/LinkinPark/p/5233182.html
Copyright © 2011-2022 走看看