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();
}
}
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();
}
}
转载于:https://blog.51cto.com/haiyuanxi/924709