静态工厂模式代码java 静态工厂类

求java工厂模式的一个简单代码例子,尽量简单这个应该比较简单一点 。
某系统日志记录器要求支持多种日志记录方式,如文件记录、数据库记录等,且用户可以根据要求动态选择日志记录方式 。现使用工厂方法模式设计该系统,并写出相应Java代码 。
interface Log{
public void writeLog();
}
class FileLog implements Log{
public void writeLog(){
System.out.println("文件记录");
}
}
class DatabaseLog implements Log{
public void writeLog(){
System.out.println("数据库记录");
}
}
interface LogFactory{
public Log createLog();
}
class FileLogFactory implements LogFactory{
public Log createLog(){
return new FileLog();
}
}
class DatabaseLogFactory implements LogFactory{
public Log createLog(){
return new DatabaseLog();
}
}
public class Client{
public static void main(String[] args) {
try{
Log log;
LogFactory factory;
//这里可以改成使用DOM和Java反射机制读取XML文件,获取工厂类名
factory=new DatabaseLogFactory ();
log=factory.createLog();
log.writeLog();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
用java 编写程序写出简单的工厂模式?java中工厂模式分为:
简单工厂模式(Simple Factory)
2. 工厂方法模式(Factory Method)
3. 抽象工厂模式(Abstract Factory)
每种方法静态工厂模式代码java的实现不同
提供一个简单工厂模式静态工厂模式代码java的案例:
public abstract class Woman {
private String mySkill;
public String getMySkill() {
return mySkill;
}
public Woman() {
//System.out.println("我是女人");
}
public void setMySkill(String mySkill) {
this.mySkill = mySkill;
}
}
----------------------------
public class LovelinessWoman extends Woman{
/*
* 可爱型女人
*/
public LovelinessWoman()
{
String mySkill="撒过娇、出过轨、勾引领导下过水";
this.setMySkill(mySkill);
}
}
-----------------------------
public class SteelinessWoman extends Woman{
/*
* 冷酷型女人
*/
public SteelinessWoman()
{
String mySkill="装过神、弄过鬼,跟别人老公亲过嘴";
this.setMySkill(mySkill);
}
}
--------------------------------------
public class WomanMakeFactory {
public Woman findWoman(int typeID) {
switch (typeID) {
case 1:
return new LovelinessWoman();
case 2:
return new VirtuousWoman();
case 3:
return new SteelinessWoman();
default:
return null;
}
}
public Woman findWoman(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
/*
* Type t = Type.GetType("SimpleFactory." + type);
* Woman wm =
* (Woman)Activator.CreateInstance(t); return wm;
*/
String string="cn.jbit.design.simplefactory."+type;
Class c = Class.forName(string);
Woman wm = (Woman) c.newInstance();
return wm;
}
}
-------------------------
调用
public class Test2 {
/**
* @param args
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Scanner input=new Scanner(System.in);
boolean sel=false;
do {
System.out.println("请选择静态工厂模式代码java你要找的女人的类型");
System.out.println("LovelinessWoman:可爱型女人 VirtuousWoman:善良型女人 SteelinessWoman:冷酷型女人");

推荐阅读