工厂模式:factory
工厂模式就相当于创建实例对象的new,用于制造孩子的机器
创建对象的一般方法: Sample s=new Sample();
示例代码:
/**
* 2设计模式之工厂模式(factory)
*
* @time 下午05:10:37
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class Factory {
//
public static Sample creator(int witch) {
if (1 == witch) {
return new SampleA();
} else if (2 == witch) {
return new SampleB();
}
return null;
}
}
/**
* 抽象工厂
*
* @time 下午05:24:39
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public abstract class Factory1 {
public abstract Sample creator();
public abstract Sample2 creator(String name);
}
public class SimpleFactory extends Factory1 {
@Override
public Sample creator() {
return new SampleA();
}
@Override
public Sample2 creator(String name) {
return new Sample2();
}
}
public class BombFactory extends Factory1 {
@Override
public Sample creator() {
return new Sample2A();
}
@Override
public Sample2 creator(String name) {
return new Sample2B();
}
}
public abstract class ForumFactory {
// 同步锁对象
private static Object initLock = new Object();
private static ForumFactory factory = null;
private static String className = "";
public static ForumFactory getInstance(Authorization authorization)
{
// 如果没授权f
if (null == authorization) {
return null;
}
// 使用单态模式
if (null == factory) {
synchronized (initLock) {
try {
// 动态转载类
Class clazz = Class.forName
(className);
factory = (ForumFactory)
clazz.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
// 返回代理对象,用作权限控制
return null;
}
}
java 设计模式学习笔记二 工厂模式Factory
最新推荐文章于 2024-11-09 23:29:17 发布