Javaファクトリモード


Javaファクトリモードは3種類ございます
1、単純工場モード(静的工場モードとも呼ばれる)
コード:
package simplefactory;

public interface Person {
	public void say();
}

 
package simplefactory;

public class Chinese implements Person{

	public void say() {
		System.out.println("I am Chinese.");
	}

}

 
package simplefactory;

public class Japanese implements Person {

	public void say() {
		System.out.println("I am Japanese.");
	}

}

 
package simplefactory;

public class PersonCreator {
	public Person createPerson(String type) {
		if (type.equals("chn")) {
			return new Chinese();
		}
		if (type.equals("jpn")) {
			return new Japanese();
		}

		return null;
	}
}

 
package simplefactory;

public class Test {
	public static void main(String[] args) {
		PersonCreator pc = new PersonCreator();
		pc.createPerson("chn").say();
		pc.createPerson("jpn").say();
	}
}

 2、抽象工場モデル
コード:
package factorymethod
public abstract class AbstractFactory {
	public abstract Person create();
}

 
package factorymethod;

public class Chinese extends Person{

	public void say() {
		System.out.println("I am Chinese.");
	}

}

 
package factorymethod;

public class Japanese extends Person {

	public void say() {
		System.out.println("I am Japanese.");
	}

}

 
package factorymethod;

public interface AbstractFactory {
	public Person create();
}

 
package factorymethod;

public class ChineseFactory implements AbstractFactory {

	public Person create() {

		return new Chinese();
	}

}

 
package factorymethod;

public class JapaneseFactory implements AbstractFactory {

	public Person create() {

		return new Japanese();
	}

}

 
package factorymethod;

public class Test {
	public static void main(String[] args) {
		ChineseFactory cf = new ChineseFactory();
		cf.create().say();
		JapaneseFactory jf = new JapaneseFactory();
		jf.create().say();
	}
}

 3、抽象工場モデル
コード:
package abstractfactory;

public interface Person {
	public void say();
}

 
package abstractfactory;

public class Chinese implements Person{

	public void say() {
		System.out.println("I am Chinese.");
	}

}

 
package abstractfactory;

public class Japanese implements Person {

	public void say() {
		System.out.println("I am Japanese.");
	}

}

 
package abstractfactory;

public abstract class AbstractFactory {
	public abstract Chinese createChinese();
	public abstract Japanese createJapanese();
}

 
package abstractfactory;

public class DefaultFactory extends AbstractFactory{

	public Chinese createChinese() {
		return new Chinese();
	}

	public Japanese createJapanese() {
		return new Japanese();
	}

}

 
package abstractfactory;

public class Test {
	public static void main(String[] args) {
		AbstractFactory af = new DefaultFactory();
		af.createChinese().say();
		af.createJapanese().say();
	}
}