抽象工厂模式,秒懂

设计模式-抽象工厂模式

抽象工厂模式属于创建型模式

它是工厂模式的延伸。

在工厂模式中,工厂是具体的,产品是抽象的,
现在工厂也是抽象的,抽象工厂中的工厂相当于工厂模式中的产品。

可能会有一点绕口,不过没理解也没关系,
这里的代码量不多,一共七个类,
一起写下来,大家肯定会对抽象工厂模式有一个自己的认识,包教包会。

实例

抽象生物类

public interface Species {

	/**
	 * 生物的行为
	 */
	void action();
	
}

抽象工厂类

public interface AbstractFactory {

	/**
	 * 创造一种生物
	 * @param kind 物种
	 * @return
	 */
	Species createSpecies(String kind);
	
}

植物-小草类

public class Weed implements Species {

	@Override
	public void action() {
		// TODO Auto-generated method stub
		System.out.println("小草发芽!");
	}

}

动物-小羊类

public class Sheep implements Species {

	@Override
	public void action() {
		// TODO Auto-generated method stub
		System.out.println("小羊吃草!");
	}

}

具体工厂-植物工厂

public class PlantFactory implements AbstractFactory {

	@Override
	public Species createSpecies(String kind) {
		// TODO Auto-generated method stub
		if ("weed".equals(kind)) {
			return new Weed();
		}
		if ("otherPlant".equals(kind)) {
			// 其它的植物
		}
		return null;
	}

}

具体工厂-动物工厂

public class AnimalFactory implements AbstractFactory {

	@Override
	public Species createSpecies(String kind) {
		// TODO Auto-generated method stub
		if ("sheep".equals(kind)) {
			return new Sheep();
		}
		if ("otherAnimal".equals(kind)) {
			// 其它的动物
		}
		return null;
	}

}

测试类

public class Test {

	public static void main(String[] args) {
		// 植物工厂
		AbstractFactory plantFactory = getFactory("plant");
		// 小草
		Species plant = plantFactory.createSpecies("weed");
		plant.action();
		
		// 动物工厂
		AbstractFactory animalFactory = getFactory("animal");
		// 小羊
		Species animal = animalFactory.createSpecies("sheep");
		animal.action();
	}
	
	/**
	 * 先用工厂模式获取具体工厂
	 * @param type
	 * @return
	 */
	private static AbstractFactory getFactory (String type) {
		if ("plant".equals(type)) {
			return new PlantFactory();
		}
		if ("animal".equals(type)) {
			return new AnimalFactory();
		}
		if ("others".equals(type)) {
			
		}
		return null;
	}
	
}

运行结果

在这里插入图片描述
这样对调用者来说会很友好,
只需要知道动物animal>羊sheep吃植物plant>草weed就可以了。

不当之处,请予指正。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值