Java中的簡單工廠設計模式

pangqiandou發表於2017-09-12
package cn.mldn.demo;
//設計模式:簡單工廠設計模式
interface Fruit{
public 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 fruit=null;
if("apple".equals(className)){
fruit=new Apple();
}else if("orange".equals(className)){
fruit=new Orange();
}
return fruit;
}
}
public class FactoryCaseDemo {
public static void main(String[] args) {
Fruit fruit=null;
fruit=Factory.getInstance("apple");
fruit.eat();
fruit=Factory.getInstance("orange");
fruit.eat();
}
}

相關文章