【Design Pattern】Factory

1582 ワード

1.製品インタフェース、製品実現類は簡単な工場と同じである
package Factory;

public interface Animal {
	
	public void makeSound();

}
package Factory;

public class Dog implements Animal{

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

public class Cat implements Animal{

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

2.工場インタフェース類
package Factory;

public interface AnimalFactory {
	
	public Animal createAnimal();
}

3.工場実現類
package Factory;

public class DogFactory implements AnimalFactory{

	@Override
	public Animal createAnimal() {
		return new Dog();
	}
}
package Factory;

public class CatFactory implements AnimalFactory{

	@Override
	public Animal createAnimal() {
		return new Cat();
	}

}

4.demo
package Factory;

public class AnimalFactoryDemo {
	
	public static void main(String[] args){
		AnimalFactory dogfactory = new DogFactory();
		dogfactory.createAnimal().makeSound();
		AnimalFactory catfactory = new CatFactory();
		catfactory.createAnimal().makeSound();
	}
}