设计模式之工厂设计模式
工厂方法模式的定义:
定义一个用于创建对象的接口,让子类决定实例化哪一个类,Factory Method使一个类的实例化延迟到其子类。
package com.itmyhome; interface Fruit{ //定义一个创建对象的接口 public void eat(); } class Apple implements Fruit{ public void eat() { // TODO Auto-generated method stub System.out.println("***吃苹果***"); } } class Orange implements Fruit{ public void eat() { // TODO Auto-generated method stub System.out.println("***吃橘子***"); } } class Factory{ //工厂类 public static Fruit getInstance(String className){ Fruit fruit = null; try{ fruit = (Fruit)Class.forName(className).newInstance(); }catch(Exception e){ e.printStackTrace(); } return fruit; } } public class FactoryTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Fruit f = Factory.getInstance("com.itmyhome.Apple"); if(f!=null){ f.eat(); //***吃苹果*** } } }