interface FruitInterface {
void eat();
}
class Apple
implements FruitInterface{
@Override
public
void eat() {
// TODO Auto-generated method stub
System.out.println(
"吃蘋果");
}
}
public
class Orange
implements FruitInterface{
@Override
public
void eat() {
// TODO Auto-generated method stub
System.out.println(
"吃橘子");
}
}
public
class Factory {
//定義工廠類
public
static FruitInterface getInstance(String className){
FruitInterface fruit =
null;
if (
"Apple".equals(className)) {
//將字符串放在前面能夠避免空值
fruit =
new Apple();
}
if (
"Orange".equals(className)) {
fruit =
new Orange();
}
return fruit;
}
}
public
class FirstDemo {
/**
* 工廠設計模式
*/
public
static
void main(String[] args) {
FruitInterface fruitInterface = Factory.getInstance(
"Apple");
fruitInterface.eat();
FruitInterface fruitInterface2 = Factory.getInstance(
"Orange"); fruitInterface2.eat(); } }