简单工厂模式
简单工厂模式实际上不属于java21种标准设计模式之一,属于创建型设计模式。
工厂模式
工厂模式,类似于工厂,用来批量创建相同类型的对象。简单工厂模式就是简单的创建一类对象。
有视频这样一个类,它下面有Java视频和Python视频,现在有一个简单工厂用来生产对应的视频
元素
视频
public interface Video {
void make();
}
Java视频
public class JavaVideo implements Video {
@Override
public void make() {
System.out.println("已制作Java视频");
}
}
Python视频
public class PythonVideo implements Video {
@Override
public void make() {
System.out.println("已制作Python视频");
}
}
视频工厂类
public class VideoFactory {
public Video getVideo1(String type) {
if (type.equalsIgnoreCase("java")) {
return new JavaVideo();
} else if (type.equalsIgnoreCase("python")) {
return new PythonVideo();
}
return null;
}
}
根据传入的类型创建对应的视频
改进版2.0
public class VideoFactory {
public Video getVideo(Class c) {
Video video = null;
try {
video = (Video) c.getDeclaredConstructor(null).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return video;
}
}
利用反射直接创建对应的对象,从而避免大量的逻辑判断。
简单工厂模式比较简单,使用于简单类的工厂创建
实例案例
Calendar类创建日历createCalendar(TimeZone zone, Locale aLocale)里面
if (cal == null) {
if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
cal = new BuddhistCalendar(zone, aLocale);
} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
&& aLocale.getCountry() == "JP") {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
}
LoggerFactory获取Logger
LoggerFactory.getLogger(DemoApplication.class);
@Override
public final Logger getLogger(final String name) {
if (name == null) {
throw new IllegalArgumentException("name argument cannot be null");
}
// 这里根据名字进行判断,并返回不同的Logger
if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) {
return root;
}
int i = 0;
Logger logger = root;
// check if the desired logger exists, if it does, return it
// without further ado.
Logger childLogger = (Logger) loggerCache.get(name);
// if we have the child, then let us return it without wasting time
if (childLogger != null) {
return childLogger;
}
// if the desired logger does not exist, them create all the loggers
// in between as well (if they don't already exist)
String childName;
while (true) {
int h = LoggerNameUtil.getSeparatorIndexOf(name, i);
if (h == -1) {
childName = name;
} else {
childName = name.substring(0, h);
}
// move i left of the last point
i = h + 1;
synchronized (logger) {
childLogger = logger.getChildByName(childName);
if (childLogger == null) {
childLogger = logger.createChildByName(childName);
loggerCache.put(childName, childLogger);
incSize();
}
}
logger = childLogger;
if (h == -1) {
return childLogger;
}
}
}