设计模式

来源:互联网 发布:vb语言用处 编辑:程序博客网 时间:2024/06/07 06:50

简单工厂模式(静态工厂模式): 类提供一个公有的静态工厂方法,返回一个类的的实例.

案例1: Java 中基本类型的包装类工厂方法:

public static Integer valueOf(int i) {    if (i >= IntegerCache.low && i <= IntegerCache.high)        return IntegerCache.cache[i + (-IntegerCache.low)];    return new Integer(i);}
案例2: 一个类的继承层次中,Employee 是父类,子类有 Engineer, Sales, Manager, 可以在Employee类添加一个参数化的创建方法来创建子类实例:

static Employee create(String className) { //className "Engineer", "Sales" or "Manager"try { return (Employee) Class.forName(className).newInstance();} catch(Exception e) {throw new IllegalArgumentException("Unable to instantiate " + className);}}
案例3: 单件模式, 如log4j API
public static Logger getLogger(String name)

静态工厂方法相对于公有构造器优势有:

1. 它有名字,可以确切的描述返回的对象; 构造器名字相同,如果有两个构造器,他们的参数列表的类型一样,只是顺序不一样,无法记住该用哪个构造器;

2. 不必每次调用的时候都创建一个新对象,如单件模式创建全局对象; 对象缓存技术, 如:

多个订单Order属于一个客户Customer,将客户对象缓存到一个Map对象中<name, customer>, 使用时先根据name从Map对象中查找,如果没有再创建,然后缓存起来。

public class CustomerService{    private static Map<String,Customer> customers = new HashMap<String, Customer>();    public static createCustomer(String name) {Customer customer = customers.get(name);if(customer != null) return customer;if(customer == null) {    customer = new Customer(name);    customers.put(name, customer);    return customer;}     }}
3. 可以返回原返回类型的任何子类, 如Java的Collections集合接口提供了不可修改的的集合、同步集合等

<T> Set<T> java.util.Collections.unmodifiableSet(Set<? extends T> s)





0 0