创建型设计模式--简单工厂

 

简单工厂(静态工厂方法Static Factory Method模式)

   

    简单工厂模式是由一个工厂对象来决定创造哪一种产品类的实例

 

    简单工厂模式最大的优点在于工厂类中包含了必要的逻辑判断。

 

 

 

// 产品接口---水果接口
public interface Fruit {
	public void plant();
}

// 产品----苹果类
public class Apple implements Fruit {
	public void plant() {
		System.out.println("plant apple!");
	}
}

// 产品----草莓类
public class Strawberry implements Fruit {
	public void plant() {
		System.out.println("plant Strawberry!");
	}
}

// 工厂异常类
public class BadFruitException extends Exception {
	public BadFruitException(String msg) {
		super(msg); // 调用父类的构造方法
	}
}

// 工厂----园丁类
public class FruitGardener {// 静态工厂方法
	public static Fruit factory(String which) throws BadFruitException {
		if (which.equalsIgnoreCase("apple")) {
			return new Apple();
		} else if (which.equalsIgnoreCase("strawberry")) {
			return new Strawberry();
		} else {
			throw new BadFruitException("Bad fruit request");
		}
	}
}

// 测试类
public class TestApp {
	private void test(String fruitName) {
		try {
			Fruit f = FruitGardener.factory(fruitName);
			System.out.println("恭喜!生产了一个水果对象:" + fruitName);
		} catch (BadFruitException e) {
			System.out.println("工厂目前不能生产产品:" + fruitName);
			System.out.println(e.getMessage());// 输出异常信息
		}
	}

	public static void main(String args[]) {
		TestApp t = new TestApp();
		t.test("apple");
		t.test("strawberry");
		t.test("car"); // 此处会抛异常,水果工厂能生产car(轿车)吗!
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值