简单工厂设计模式实现

主要用到概念:接口,抽象方法,覆写,static定义变量,主方法中的匿名对象使用。

代码如下:

package factory;

interface fruit {
public abstract void eat();
}

class Apple implements fruit {
public void eat() {
System.out.println("eat apple");
}
}

class Orange implements fruit {
public void eat() {
System.out.println("eat orange");
}
}

class Banana implements fruit {
public void eat() {
System.out.println("eat banana");
}
}

class factory {
public static String APPLE = "apple";
public static String ORANGE = "orange";
public static String BANANA = "banana";

public static fruit getInstance(String className) {
if (APPLE.equals(className)) {
return new Apple();
} else if (ORANGE.equals(className)) {
return new Orange();
} else if (BANANA.equals(className)) {
return new Banana();
}
return null;
}
}

public class demo {
public static void main(String[] args) {
fruit f = factory.getInstance("apple");
f.eat();
}
}
上一篇:002-ES6Class和普通构造函数的区别


下一篇:前方高能 - 面向对象初识