单例(Singleton)设计兼谈工厂 要求:创建一个类,此类不能被外界,只能调用对外提供的接口来拿到该类的实例,要求每次返回的都是该类相同的实例。 示例代码: Student.java package org.chinasoft.dp; public class Student { private static Student student = new Student(); private Student() { } public static Student getInstance() { return student; } public String toString() { return "Hello Student"; } } 每次返回的都是同一个Student的实例化对象。 ONLY ONE ENTITY 工厂设计 简单的对象工厂 示例代码: package org.chinasoft.dp; public class Car { private static Car car = new Car(); private Car() { } public static Car getInstance() { return car; } public String toString() { return "Hello Car"; } } Factory.java package org.chinasoft.dp; public class Factory { public static int size; public static int current; private static Object[] object; private Factory() { } public static void product(Object o) { if(object == null) { object = new Object[10]; size = 10; } object[current++] = o; if(current == size) { Object[] newObject = new Object[current + 10]; System.arraycopy(object, 0, newObject, 0, object.length); object = newObject; } } public static Object[] getInstance() { return object; } } 测试类:Test.java package org.chinasoft.dp; public class Test { public static void main(String[] args) { Student student = Student.getInstance(); Car car = Car.getInstance(); Factory.product(student); Factory.product(car); Object[] o = Factory.getInstance(); for(Object obj : o) { if(obj == null) return; if(obj instanceof Student) { Student stu = (Student)obj; System.out.println(stu); } if(obj instanceof Car) { Car c = (Car)obj; System.out.println(c); } } } } 程序的运行结果: Hello Student Hello Car Factory表示工厂类,此类有一个product方法可以产生一个对象,并将产生的对象添加到工厂的对象集合中保存;Factory类本身就是一个单例设计。 静态工厂方法-简单工厂-抽象工厂
posted on 2010-10-24 19:04 freehell 阅读(128) 评论(0) 编辑 收藏 举报
Powered by: 博客园 Copyright © 2024 freehell Powered by .NET 8.0 on Kubernetes