[Design pattern] Abstract Factory Methods ๐Ÿ–‡, (Creational patterns)

14184 ๋‹จ์–ด Design PatternDesign Pattern

Overview

Abstract Factory Pattern ๐Ÿ–‡

ย  ย ์—ฐ๊ด€๋œ ์„œ๋ธŒ ํด๋ž˜์Šค๋ฅผ ํŠน์ • ๊ทธ๋ฃน์œผ๋กœ ๋ฌถ์–ด ํ•œ ๋ฒˆ์— ๊ต์ฒด ๊ฐ€๋Šฅํ•˜๊ฒŒ ๋งŒ๋“  ๋””์ž์ธ ํŒจํ„ด Factory method์˜ ํ™•์žฅ์ด๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๋‹ค.


Class Diagram


Example Code ๐Ÿ“ƒ

package abstractfactory;

public interface MachineA {
	public void process();
}
package abstractfactory;

public class MachineA1 implements MachineA{

	@Override
	public void process() {
		System.out.println("excute MachineA1");
	}
}
package abstractfactory;

public class MachineA2 implements MachineA{

	@Override
	public void process() {
		System.out.println("excute MachineA2");
	}
}

package abstractfactory;

public interface MachineB {
	public void process();
}
package abstractfactory;

public class MachineB1 implements MachineB{

	@Override
	public void process() {
		System.out.println("excute MachineB1");
	}
}
package abstractfactory;

public class MachineB2 implements MachineB{

	@Override
	public void process() {
		System.out.println("excute MachineB1");
	}
}

package abstractfactory;

public interface MachineFactory {
	public MachineA getMachineA();
	public MachineB getMachineB();
}
package abstractfactory;

public class MachineFactoryA implements MachineFactory{

	@Override
	public MachineA getMachineA() {
		return new MachineA1();
	}

	@Override
	public MachineB getMachineB() {
		return new MachineB1();
	}
}
package abstractfactory;

public class MachineFactoryB implements MachineFactory{

	@Override
	public MachineA getMachineA() {
		return new MachineA2();
	}

	@Override
	public MachineB getMachineB() {
		return new MachineB2();
	}
}

Main Program ๐Ÿ“‘

package abstractfactory;

public class FactoryMain {

	public static void main(String[] args) {
		MachineFactory machineFactoryA = new MachineFactoryA();
		machineFactoryA.getMachineA().process();
		machineFactoryA.getMachineB().process();

		MachineFactory machineFactoryB = new MachineFactoryB();
		machineFactoryB.getMachineA().process();
		machineFactoryB.getMachineB().process();
	}
}
excute MachineA1
excute MachineB1
excute MachineA2
excute MachineB1

์ž˜ ๋™์ž‘ํ•œ๋‹ค.


Closing Remarks ๐Ÿšฉ

Abstract Factory Pattern

ย  ย ๋™์ผํ•œ ์ฒ˜๋ฆฌ ๋กœ์ง์˜ ํ•˜์œ„ ํด๋ž˜์Šค์˜ ๊ฒฐํ•ฉ์„ ํ†ตํ•ด ์„ ํƒ์ ์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. ๋‹ค๋งŒ, ์ƒˆ๋กœ์šด ๊ฐ์ฒด๊ฐ€ ์ถ”๊ฐ€๋œ๋‹ค๋ฉด ํ•˜์œ„ ํด๋ž˜์Šค๋„ ๊ฐ™์ด ์ถ”๊ฐ€ํ•ด์•ผ ๋˜๊ณ  ํ™•์žฅ ์‹œ ๋ชจ๋“  ํ•˜์œ„ ํด๋ž˜์Šค์˜ ์ˆ˜์ •์ด ํ•„์š”ํ•  ์ˆ˜๋„ ์žˆ๋‹ค.


Factory method

ย  ย 1๊ฐœ์˜ ํ•˜์œ„ ํด๋ž˜์Šค ๋‚ด ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ํ†ตํ•ด ์ƒ์„ฑ์„ ์„ ํƒ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋ฏ€๋กœ ๋‹คํ˜•์„ฑ์˜ ๋‹จ์ ์„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.
๋‹ค๋งŒ, ์ƒˆ๋กœ์šด ๊ฐ์ฒด๊ฐ€ ์ถ”๊ฐ€๋œ๋‹ค๋ฉด ์กฐ๊ฑด์ด ์ถ”๊ฐ€๋˜์–ด์•ผ ํ•˜๊ณ  ํ™•์žฅ ์‹œ ํ•˜์œ„ ํด๋ž˜์Šค์˜ ๊ทœ๋ชจ๊ฐ€ ์ปค์ง€๊ธฐ ๋•Œ๋ฌธ์— ์œ ์ง€ ๋ณด์ˆ˜๊ฐ€ ์–ด๋ ค์šธ ์ˆ˜ ์žˆ๋‹ค.


์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ