Java 简单工厂设计模式示例:水果类
public class Test { public static void main(String[] args) { Fruit apple = Factory.getInstance('apple'); apple.eat(); // 输出:吃苹果
Fruit orange = Factory.getInstance('orange');
orange.eat(); // 输出:吃橘子
}
}
interface Fruit { void eat(); }
class Apple implements Fruit { @Override public void eat() { System.out.println('吃苹果'); } }
class Orange implements Fruit { @Override public void eat() { System.out.println('吃橘子'); } }
class Factory { public static Fruit getInstance(String className) { Fruit f = null; if ('apple'.equals(className)) { f = new Apple(); } if ('orange'.equals(className)) { f = new Orange(); } return f; } }
原文地址: https://www.cveoy.top/t/topic/mWA4 著作权归作者所有。请勿转载和采集!