编写工厂模式的JAVA程序_用java 编写程序写出简单的工厂模式?

展开全部

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值