设计模式-工厂模式



工厂模式属于创建型模式

它提供了一种基于"输入"的创建对象方式。

应用场景

超类存在多个子类时创建对象,
创建过程比较复杂的对象,适合使用工厂模式,
过程简单,不需要使用工厂模式。

实例

动物类

package com.superv.supervresource.design.factory;

/**
 * @author yangwei
 * @describition 动物
 *
 * @time 2020年10月26日-下午7:10:32
 */
public interface Animal {

	void eat ();
	
}

小羊类

package com.superv.supervresource.design.factory;

/**
 * @author yangwei
 * @describition 羊
 *
 * @time 2020年10月26日-下午7:13:45
 */
public class Sheep implements Animal {

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

}

小猫类

package com.superv.supervresource.design.factory;

/**
 * @author yangwei
 * @describition 猫
 *
 * @time 2020年10月26日-下午7:12:45
 */
public class Cat implements Animal {

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("小猫吃鱼。");
	}

}

工厂类

package com.superv.supervresource.design.factory;

/**
 * @author yangwei
 * @describition 动物工厂
 *
 * @time 2020年10月26日-下午7:14:13
 */
public class AnimalFactory {

	public static Animal getAnimal (String animalType) {
		if ("sheep".equals(animalType)) {
			return new Sheep();
		}
		if ("cat".equals(animalType)) {
			return new Cat();
		}
		return null;
	}
	
}

工厂测试类

package com.superv.supervresource.design.factory;

/**
 * @author yangwei
 * @describition 工厂测试类
 *
 * @time 2020年10月26日-下午7:16:34
 */
public class AnimalFactoryTest {

	public static void main(String[] args) {
		Animal sheep = AnimalFactory.getAnimal("sheep");
		sheep.eat();
		Animal cat = AnimalFactory.getAnimal("cat");
		cat.eat();
	}
	
}

运行结果

在这里插入图片描述
不当之处,请予指正。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值