首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

静态工场方法

2012-08-24 
静态工厂方法它只是一个简单的静态方法,返回类的一个实例.1. 与构造函数不同,静态工厂方法具有名字.选用适

静态工厂方法
它只是一个简单的静态方法,返回类的一个实例.

1. 与构造函数不同,静态工厂方法具有名字.选用适当名字的静态工厂方法可以使一个类更易于使用,并且相应的客户代码更易于阅读.

2. 与构造函数不同,不要求非得创建一个新的对象.这使得一些非可变类可以使用一个预先构造好的实例,或者把已经构造好的实例缓冲起来.同时,静态工厂方法可以为重复的调用返回同一个对象,这也可以被用来控制"在某一时刻哪些实例应该存在."   好处1:使得一个类可以保证是一个singleton.  好处2:使非可变类可以保证"不会有两个相等的实例存在",即当且仅当a==b时才有a.equals(b)为true.这可以提高性能.

3. 与构造函数不同,它们可以返回一个原返回类型的子类型的对象.特别是,能够返回实现类对于调用者隐藏的对象.这项技术非常适合于基于接口的框架结构,因为这样的框架结构中,接口成为静态工厂方法的自然返回类型.调用者只能通过接口来引用被返回的对象,而不能通过实现类来引用被返回的对象.

静态工厂方法的命名包括getInstance和valueOf,但这并不是强制要求的,只要具有明确的意义即可.

示例:
public class ComplexNumber {

  /**
  * Static factory method returns an object of this class.
  */
  public static ComplexNumber valueOf(float aReal, float aImaginary) {
    return new ComplexNumber(aReal, aImaginary);
  }

  //private constructor prevents subclassing
  private ComplexNumber (float aReal, float aImaginary) {
    fReal = aReal;
    fImaginary = aImaginary;
  }

  private float fReal;
  private float fImaginary;
}

JDK2中的示例:

LogManager.getLogManager
public static LogManager getLogManager() {
        if (manager != null) {
            manager.readPrimordialConfiguration();
        }
    return manager;
}

Pattern.compile
public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
}

Collections.unmodifiableCollection, Collections.synchronizeCollection等等
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
    return new UnmodifiableCollection<T>(c);
}
    public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
    return new SynchronizedCollection<T>(c);
}

Calendar.getInstance
public static Calendar getInstance(){
        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault());
    cal.sharedZone = true;
    return cal;
}

与reflection一起作用:

对象实例可以由user input,config file,或者任意来源决定.
完全支持在runtime时决定需要的对象实例.

public class Creator {

    // #1: basic static factory method
    protected static Hello createHelloer() {
        return new HelloWorld();
    }

    // #2: parameted static factory method
    protected final static int WORLD = 1;

    protected final static int CAMEL = 2;

    protected static Hello createHelloer(int id) {
        if (id == 1) {
            return new HelloWorld();
        }
        if (id == 2) {
            return new HelloCamel();
        }
        return null;
    }

    // #3: use reflection
    protected static Hello createHelloer(String name) {
        try {
            Class c = Class.forName(name);
            return (Hello) c.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        /*
         * no factory method, usual codes
         */
        HelloWorld hw = new HelloWorld();
        hw.sayHello();
        HelloCamel hc = new HelloCamel();
        hc.sayHello();
        System.out.println("===========================");
       
        /*
         * basic factory method
         *
         * for different requirement, you can new different subclass and
         * override createHelloer() to get dedicated implemented class
         */
        Hello h = createHelloer();
        h.sayHello();
        System.out.println("===========================");
       
        /*
         * parameted factory method
         */
        h = createHelloer(WORLD);
        h.sayHello();
        h = createHelloer(CAMEL);
        h.sayHello();
        /*
         * parameted factory method by reflection
         */
        System.out.println("===========================");
        h = createHelloer("HelloWorld");
        h.sayHello();
        h = createHelloer("HelloCamel");
        h.sayHello();
    }
}

interface Hello {
    void sayHello();
}

class HelloWorld implements Hello {
    public void sayHello() {
        System.out.println("Hello, World!");
    }
}

class HelloCamel implements Hello {
    public void sayHello() {
        System.out.println("Hello, Camel");
    }
}

热点排行