package gongchangdemo;
/*
* 在java开发中使用较多的一种设计模式:工厂模式:就是一个过渡端
* 通过过度端来取得接口的实例化对象,这个过渡端就称为工厂factory
* 这个模式主要是为了解决修改子类,必须要修改main方法,而main方法主要是客户端,客户端
* 经常变来变去不太好,就引进:工厂模式
*/
public class gongchangdemo {
public static void main(String args[]) {
//getinstance 方法是静态的所以可以用类名直接调用
//fruit f =null ;
//f = factory.getinstance("apple");
//f.eat();
//上面写得apple是固定的,能否通过初始化参数的方法,则可以选择任意的子类去标记
fruit f = null;
f = factory.getinstance(args[0]);
if (f!=null) {
f.eat();
}
}
}
//写一个接口
interface fruit{
//写一个吃的抽象类
public abstract void eat();
}
//写一个子类去实现fruit
class apple implements fruit{
public void eat(){
System.out.println("我在吃苹果");
}
}
//再写一个子类去实现fruit
class orange implements fruit{
public void eat(){
System.out.println("我在吃橘子");
}
}
//写一个过渡端 类factory,获取接口的实例化对象
class factory{
//返回 fruit类型的,所以用fruit修饰
public static fruit getinstance(String classname){
//先初始化
fruit f =null;
//传过来的参数与子类名对比
if ("apple".equals(classname)) {
f = new apple();
}
if ("orange".equals(classname)) {
f = new orange();
}
return f;
}
}