一起来学工厂模式

package lololo01;


interface Fruit {
public void eat();

}
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果。");
}
}
class Cherry implements Fruit{
public void eat(){
System.out.print("chi cherry");
}
}


class Factory{
public static Fruit getInstance (String className){
if("apple".equals(className)){
return new Apple();
}
else if("cherry".equals(className)){
return new Cherry();
}
else{
return null;
}
}
}
public class TestDemo{
public static void main(String args[]){
Fruit f=Factory.getInstance(args[0]);
if(f!=null){
f.eat();}
}

}

请在cmd下面进行运行,在eclipse下面进行运行的话,会出现越界问题,因为要进行传递参数。


理解工厂模式:其实就是加了一个中间的东西进行过度,如果没有工厂模式的话,比如,原先只有这样的一段程序:

interface Fruit {
public void eat();

}
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果。");
}
}

public class TestDemo{
public static void main(String args[]){
Fruit f=new Apple();
f.eat();
}

}

这只是定义了fruit接口,然后就实现接口,如果在继承fruit接口的时候,你还也想“”吃cherry“,“”吃橘子“”,那么如果你要进行添加的话,需要改动好多地方,实现接口的地方当跟上面的吃苹果是一样的:

class Orange implements Fruit{
public void eat(){
System.out.println("吃橘子");
}
}

那么问题来了,当你在main函数里面进行添加的时候,就会发现你还修改的地方很多首先这儿肯定是要进行修改的:Fruit f= new Orange();那就是说以后你每像“吃一次水果”,你都要这么麻烦,所以就引入了工厂模式,在你进行添加的时候,只需要在定义的Factory里面进行加一点东西就可以OK啦:

else if("Orange”.equals(className)){

return new Orange();

}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值