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