设计模式之接口模式

目录

接口型模式介绍

接口事例

UML图

代码

Animal接口

Cat实现

Dog实现

Test

Test输出结果

 


接口型模式介绍

接口通常代表的是一种承诺,即方法需要实现接口方法名表示的操作,Java将接口概念提升为独立的结构,体现了接口与实现的分离。

接口型模式包括:适配器模式、外观模式、合成模式、桥接模式。

 

接口事例

UML图

 

代码

Animal接口

package com.lulei.study.design.patterns.interfaceMode;

/**
 * Created by lulei on 2019/4/9.
 */
public interface Animal {
    void eat();
    void speak();
}

 

Cat实现

package com.lulei.study.design.patterns.interfaceMode.impl;

import com.lulei.study.design.patterns.interfaceMode.Animal;

/**
 * Created by lulei on 2019/4/9.
 */
public class Cat implements Animal {
    public void eat() {
        System.out.println("爱吃鱼!");
    }

    public void speak() {
        System.out.println("喵!喵!喵!");
    }
}

 

Dog实现

package com.lulei.study.design.patterns.interfaceMode.impl;

import com.lulei.study.design.patterns.interfaceMode.Animal;

/**
 * Created by lulei on 2019/4/9.
 */
public class Dog implements Animal {
    public void eat() {
        System.out.println("爱吃骨头!");
    }

    public void speak() {
        System.out.println("汪!汪!汪!");
    }
}

 

Test

package com.lulei.study.design.patterns.interfaceMode.test;

import com.lulei.study.design.patterns.interfaceMode.Animal;
import com.lulei.study.design.patterns.interfaceMode.impl.Cat;
import com.lulei.study.design.patterns.interfaceMode.impl.Dog;

/**
 * Created by lulei on 2019/4/9.
 */
public class Test {
    public static void main(String[] args) {
        Animal cat = new Cat();
        Animal dog = new Dog();
        System.out.println("-------cat-------");
        cat.eat();
        cat.speak();
        System.out.println("-------dog-------");
        dog.eat();
        dog.speak();
    }
}

 

Test输出结果

-------cat-------
爱吃鱼!
喵!喵!喵!
-------dog-------
爱吃骨头!
汪!汪!汪!

 

你可能感兴趣的:(设计模式)