展开全部
java中工厂模式分为:简单工厂模式(Simple Factory)
2. 工厂方32313133353236313431303231363533e78988e69d8331333337396238法模式(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="装过神、弄过鬼,跟别人老公亲过嘴";
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("请选择你要找的女人的类型");
System.out.println("LovelinessWoman:可爱型女人 VirtuousWoman:善良型女人 SteelinessWoman:冷酷型女人");
String typeid=input.next();
WomanMakeFactory factory = new WomanMakeFactory();
Woman wm=factory.findWoman(typeid);
System.out.println("该类型女人的新标准:");
System.out.println(wm.getMySkill());
System.out.println("还想看看别的类型吗?y代表想,n代表再也不想了");
sel=input.next().equals("y");
} while (sel);
}
}