接口--工厂设计模式

来源:互联网 发布:ps 保留图层导入Ai mac 编辑:程序博客网 时间:2024/05/22 00:58
interface Fruit{                //定义一个接口    public void eat();}class Apple implements Fruit{   //实现接口    public void eat() {        System.out.println("吃苹果");    }}class Orange implements Fruit{ //实现接口    public void eat() {        System.out.println("吃橘子");    }}class Factory{    public static Fruit getInstance(String className) {        if("apple".equals(className)) {            return new Apple();        }        if("orange".equals(className)) {            return new Orange();        }        return null;    }}public class Test {    public static void main(String[] args) {        Fruit f = Factory.getInstance("apple");        f.eat();    }}

输出结果:
吃苹果