工厂模式java代码 java中工厂模式是什么意思( 三 )


public Log createLog(){
return new DatabaseLog();
}
}
public class Client{
public static void main(String[] args) {
try{
Log log;
LogFactory factory;
//这里可以改成使用DOM和Java反射机制读取XML文件工厂模式java代码,获取工厂类名
factory=new DatabaseLogFactory ();
log=factory.createLog();
log.writeLog();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Java 工厂模式interface Fruit { // 定义一个水果接口
public void eat(); // 吃水果
}
class Apple implements Fruit {
public void eat() {
System.out.println("** 吃苹果 。");
}
};
class Orange implements Fruit {
public void eat() {
System.out.println("** 吃橘子 。");
}
};
class Factory { // 定义工厂类
private static Factory factory;
private Factory(){}
public static Factory getInstance() {
if(factory==null){
factory=new Factory();
}
return factory;
}
public Apple newApplet(){
return new Apple();
}
public Orange newOrange(){
return new Orange();
}
};
class FactoryModel {
public static void main(String args[]) {
Fruit f = Factory.getInstance().newApplet();
if (f != null) { // 判断是否取得实例
f.eat();
}
f = Factory.getInstance().newOrange();
if (f != null) { // 判断是否取得实例
f.eat();
}
}
};
用java 编写程序写出简单的工厂模式?java中工厂模式分为:
简单工厂模式(Simple Factory)
2. 工厂方法模式(Factory Method)
3. 抽象工厂模式(Abstract Factory)
每种方法的实现不同
提供一个简单工厂模式的案例:
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="装过神、弄过鬼工厂模式java代码,跟别人老公亲过嘴";
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 {

推荐阅读