程序在接口和子类之间加入一个过渡类,通过此过渡类端取得接口的实例化对象,一般都会称这个过渡端为工厂类
//================================================= // File Name : factory //------------------------------------------------------------------------------ // Author : Common // 接口名:Fruit // 属性: // 方法: interface Fruit{ public void eat(); } //类名:Apple //属性: //方法: class Apple implements Fruit{ @Override public void eat() { // TODO 自动生成的方法存根 System.out.println("eat apple!"); } } //类名:Orange //属性: //方法: class Orange implements Fruit{ @Override public void eat() { // TODO 自动生成的方法存根 System.out.println("eat orange!"); } } //类名:Factory //属性: //方法: class Factory{ //定义工厂类 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; } } //主类 //Function : 工厂设计模式 public class factory { public static void main(String[] args) { // TODO 自动生成的方法存根 Fruit f = null; //定义接口对象 f = Factory.getInstance("apple"); //通过工厂取得实例 f.eat(); //调用方法 } }
//================================================= // File Name : factory //------------------------------------------------------------------------------ // Author : Common // 接口名:Fruit // 属性: // 方法: interface Fruit{ public void eat(); } //类名:Apple //属性: //方法: class Apple implements Fruit{ @Override public void eat() { // TODO 自动生成的方法存根 System.out.println("eat apple!"); } } //类名:Orange //属性: //方法: class Orange implements Fruit{ @Override public void eat() { // TODO 自动生成的方法存根 System.out.println("eat orange!"); } } //类名:Factory //属性: //方法: class Factory{ //定义工厂类 public static Fruit getInstance(String className){ Fruit f = null; //定义接口对象 try{ f = (Fruit)Class.forName(className).newInstance(); //实例化对象 }catch(Exception e){ e.printStackTrace(); } return f; } } //主类 //Function : 工厂设计模式 public class factory { public static void main(String[] args) { // TODO 自动生成的方法存根 Fruit f = null; //定义接口对象 f = Factory.getInstance("Apple"); //通过工厂取得实例 f.eat(); //调用方法 } }
结合属性文件的工厂模式