【Design Pattern】Simple Factory

1.先写产品接口
package SimpleFactory;

public interface Animal {
	
	public void makeSound();

}


2.产品实现
package SimpleFactory;

public class Dog implements Animal{

	@Override
	public void makeSound() {
		System.out.println("wang");	
	}
}

package SimpleFactory;

public class Cat implements Animal{

	@Override
	public void makeSound() {
		System.out.println("miao");	
	}
}


3.具体工厂类
package SimpleFactory;

public class AnimalFactory {
	
	public static Animal getAnimal(String type){
		if(type == null){
			return null;
		}
		if(type.equalsIgnoreCase("Dog")){
			return new Dog();
		}else if(type.equalsIgnoreCase("Cat")){
			return new Cat();
		}
		return null;
	}
}


4.demo
package SimpleFactory;

public class AnimalFactoryDemo {
	
	public static void main(String[] args){
		Animal animal1 = AnimalFactory.getAnimal("Dog");
		animal1.makeSound();
		Animal animal2 = AnimalFactory.getAnimal("Cat");
		animal2.makeSound();
	}
}

你可能感兴趣的:(design pattern)