简单工厂SimpleFactory

简单工厂SimpleFactory

 

public interface Fruit {
	
	/**
	 * 种植
	 */
	public void plant();
	
	/**
	 * 生长
	 */
	public void grow();
	
	/**
	 * 收获
	 */
	public void harvest();
	
}

 

public class Apple implements Fruit {
	
	/**
	 * 树龄
	 */
	private int treeAge;

	public int getTreeAge() {
		return treeAge;
	}

	public void setTreeAge(int treeAge) {
		this.treeAge = treeAge;
	}

	@Override
	public void plant() {
		System.out.println("Apple has been planted.");
	}

	@Override
	public void grow() {
		System.out.println("Apple is growing...");
	}

	@Override
	public void harvest() {
		System.out.println("Apple has been harvested.");
	}

}

 

public class Grape implements Fruit {
	
	/**
	 * 葡萄籽
	 */
	private boolean seedless;

	public boolean isSeedless() {
		return seedless;
	}

	public void setSeedless(boolean seedless) {
		this.seedless = seedless;
	}

	@Override
	public void plant() {
		System.out.println("Grape has been planted.");
	}

	@Override
	public void grow() {
		System.out.println("Grape is growing...");
	}

	@Override
	public void harvest() {
		System.out.println("Grape has been harvested.");
	}

}

 

public class BadFruitException extends Exception {

	private static final long serialVersionUID = 1931482705041478631L;
	
	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("grape")) {
			return new Grape();
		} else if (which.equalsIgnoreCase("strawberry")) {
			return new Strawberry();
		} else {
			throw new BadFruitException("Bad fruit request.");
		}
	}
	
}

 

public class Strawberry implements Fruit {

	@Override
	public void plant() {
		System.out.println("Strawberry has been planted.");
	}

	@Override
	public void grow() {
		System.out.println("Strawberry is growing...");
	}

	@Override
	public void harvest() {
		System.out.println("Strawberry has been harvested.");
	}

}

 

public class TestSimpleFactory {
	
	public static void main(String[] args) {
		try {
			Apple apple = (Apple) FruitGardener.factory("apple");
			apple.plant();
			apple.grow();
			apple.harvest();
			apple.setTreeAge(2);
			System.out.println("树龄" + apple.getTreeAge() + "年。");
		} catch (BadFruitException bfe) {
			System.out.println(bfe.getMessage());
		}
	}

}

 

你可能感兴趣的:(java,java设计模式)