java设计模式-简单工厂模式

时间:2020-12-06 20:29:03

1.目录结构

java设计模式-简单工厂模式

2. 有一个接口类Fruit,里面有get方法,Apple 和 Banana实现其接口,并重写get方法

Client是程序主入口,通过FruitFactory得到Fruit子类对象

3.代码实现

Fruit,java

public interface Fruit {

public void get();

}

Apple.java

public class Apple implements Fruit{

@Override
public void get() {
// TODO Auto-generated method stub
System.out.println("得到苹果");
}

}

Banana.java

public class Banana implements Fruit{

@Override
public void get() {
// TODO Auto-generated method stub
System.out.println("得到香蕉");
}

}

FruitFactory.java

public class FruitFactory {

public static final int APPLE = 1;
public static final int BANANA = 2;

public static Fruit getFruit(int type) throws InstantiationException, IllegalAccessException{
switch (type) {
case APPLE:
return Apple.class.newInstance();
case BANANA:
return new Banana();;
default:
return null;
}
}

}

Client.java

public class Client {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit apple;
try {
apple = FruitFactory.getFruit(FruitFactory.APPLE);
apple.get();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}