简单工厂(Simple Factory)模式
简单点讲.就是实例化的过程(也就是new一个对象)我们交给工厂去解决,我们只需告诉工厂我们需要什么
public interface Fruit {
String NAME_APPLE = "apple";
String NAME_BANNANA = "banana";
void getName();
}
public class Apple implements Fruit{
@Override
public void getName() {
System.out.println("我是苹果");
}
}
public class Banana implements Fruit{
@Override
public void getName() {
System.out.println("我是香蕉");
}
}
public class Factory {
public static Fruit getFruit(String fruitName){
if(fruitName.equals(Fruit.NAME_APPLE)){
return new Apple();
}else if(fruitName.equals(Fruit.NAME_BANNANA)){
return new Banana();
}
return null;
}
}
public class Demo {
public static void main(String[] args) {
Fruit fruit = Factory.getFruit(Fruit.NAME_APPLE);
fruit.getName();
}
}
控制台console:
我是苹果