工厂设计模式

来源:互联网 发布:python png alpha合成 编辑:程序博客网 时间:2024/06/07 14:36

普通工的厂设计模式

interface Fruit{    public void eat();}class Apple implements Fruit{    public void eat()    {        System.out.println("eat apple");    }}class Oranage implements Fruit{    public void eat()    {        System.out.println("eat orange");    }}class Factory{    public static Fruit getFruit()    {        Fruit fruit=null;        fruit= new Apple();        return fruit;    }}public class Test{    public static void main(String args[])    {        Apple apple=(Apple)Factory.getFruit();        apple.eat();    }}

这里的工厂设计模式的缺点是:如果要取得orange类的实例,则还要修改工厂类。此时可以利用反射的机制进行完善。代码如下:

package com.xing.hang;interface Fruit{    public void eat();}class Apple implements Fruit{    public void eat()    {        System.out.println("eat apple");    }}class Orange implements Fruit{    public void eat()    {        System.out.println("eat orange");    }}class Factory{    public static Fruit getFruit(String str) throws Exception    {        Fruit fruit=null;        fruit= (Fruit)Class.forName(str).newInstance();        return fruit;    }}public class Test{    public static void main(String args[]) throws Exception    {        Apple apple=(Apple)Factory.getFruit("com.xing.hang.Apple");        Orange orange=(Orange)Factory.getFruit("com.xing.hang.Orange");        apple.eat();        orange.eat();    }}
0 0