工厂模式分析----Factory Pattern

[size=large]工厂模式定义:实例化对象,用工厂方法代替new操作。
工厂模式是我们最常用的模式了,因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a=new A() 工厂模式也是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑使用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。那么具体怎么用呢?代码奉上[/size]

/**
* 生产枪的工厂接口
*
* @author Star
*
*/
public interface GunFactory {
public Gun createFootGun();// 创建步枪

public Gun createHandGun();// 创建手(***)枪

public Gun createQuickGun();// 创建冲锋枪
}



/**
* 生产便宜一类枪
*
* @author Star
*
*/
public class CheapGunFactory implements GunFactory {

public Gun createFootGun() {
return new FootGun("小米加步枪", 50);
}

public Gun createHandGun() {
return new HandGun("三八大盖", 20);
}

public Gun createQuickGun() {
return new QuickGun("解放军冲锋枪", 100);
}

}


/**
* 贵的一类枪
* @author Star
*
*/
public class ExpensiveGunFactory implements GunFactory {

public Gun createFootGun() {

return new FootGun("德国造步枪", 150);
}

public Gun createHandGun() {
return new FootGun("美国造手(***)枪", 120);

}

public Gun createQuickGun() {
return new FootGun("AK47", 250);

}

}

枪的具体类

/**
* 枪的接口类
*
* @author Star
*
*/
public abstract class Gun {
protected String gunName;// 枪名
protected int power;// 杀伤力

// 射击
public void shoot() {
System.out.println(gunName+" 射击的杀伤力为: "+power);
}

public Gun(String gunName, int power) {
this.gunName = gunName;
this.power = power;
}
}


/**
* 步枪
* @author Star
*
*/
public class FootGun extends Gun{

public FootGun(String gunName, int power) {
super(gunName, power);
}

//射击
public void shoot() {
super.shoot();
}

}


/**
* 手(***)枪
* @author Star
*
*/
public class HandGun extends Gun {

public HandGun(String gunName, int power) {
super(gunName, power);
}

public void shoot() {
super.shoot();
}

}


/**
* 冲锋枪
* @author Star
*
*/
public class QuickGun extends Gun {

public QuickGun(String gunName, int power) {
super(gunName, power);
}

public void shoot() {
super.shoot();
}
}

主函数测试类

public class FactoryMain {

public static void main(String[] args) {
GunFactory factory = new CheapGunFactory();
Gun gun = factory.createHandGun();
gun.shoot();
gun = factory.createFootGun();
gun.shoot();
gun = factory.createQuickGun();
gun.shoot();

factory = new ExpensiveGunFactory();
gun = factory.createHandGun();
gun.shoot();
gun = factory.createFootGun();
gun.shoot();
gun = factory.createQuickGun();
gun.shoot();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值