简单工厂(SimpleFactory)

本文介绍了简单工厂模式的基本概念及其在实际编程中的应用。通过一个具体的示例——动物工厂,展示了如何利用简单工厂模式来实现对象的创建过程。该模式简化了客户端代码,使得程序更加灵活且易于扩展。

基本介绍:

    简单工厂模式又称为静态工厂方法模式属于类的创建型模式
    而它的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类的实例。 也就是生产你要创建的实体对象 。简单工厂模式实际上不属于23个GOF模式,但他可以作为工厂方法模式的一个引导.


示例代码:

package org.brando;

import org.brando.AnimalFactory.AnimalType;

/**
 * 
 * 类说明: 测试类
 * @author Brando 2018年3月29日 下午2:03:59
 */
public class Launcher {

	public static void main(String[] args) {
		
		IAnimal animal_1 = AnimalFactory.createAnimal(AnimalType.DOG);
		animal_1.show();
		
		IAnimal animal_2 = AnimalFactory.createAnimal(AnimalType.CAT);
		animal_2.show();
		
	}
	
}

package org.brando;

/**
 * 
 * 类说明: 动物接口
 * @author Brando 2018年3月29日 下午3:07:36
 */
public interface IAnimal {
	
	/**
	 * 
	 * 方法说明: show自己.
	 * @author Brando 2018年3月29日 下午3:07:59
	 */
	public void show();

}

package org.brando;

/**
 * 
 * 类说明: 狗
 * @author Brando 2018年3月29日 下午3:08:43
 */
public class Dog implements IAnimal {

	@Override
	public void show() {
		System.out.println("汪汪汪");
	}

}

package org.brando;

/**
 * 
 * 类说明: 猫
 * @author Brando 2018年3月29日 下午3:09:14
 */
public class Cat implements IAnimal {

	@Override
	public void show() {
		System.out.println("喵喵喵");
	}

}

package org.brando;

/**
 * 
 * 类说明: 动物工厂类.
 * @author Brando 2018年3月29日 下午3:10:15
 */
public class AnimalFactory {

	/**
	 * 
	 * 方法说明: 创建动物.
	 * @author Brando 2018年3月29日 下午3:12:40
	 * @param type 动物类型的枚举
	 * @return
	 */
	public static IAnimal createAnimal(AnimalType type) {
		
		System.out.println("创建的动物是:" + type.name);
		
		switch (type) {
		case DOG:
			return new Dog();
		case CAT:
			return new Cat();
		default:
			return null;
		}
		
	}
	
	/**
	 * 
	 * 枚举说明: 动物类型.
	 * @author Brando 2018年3月29日 下午3:11:56
	 */
	public enum AnimalType {
		DOG("狗"), CAT("猫");
		
		private String name;
		
		AnimalType(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值