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

홍정완·2021λ…„ 8μ›” 4일
0

Design pattern

λͺ©λ‘ 보기
4/7
post-thumbnail

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개의 ν•˜μœ„ 클래슀 λ‚΄ λ§€κ°œλ³€μˆ˜λ₯Ό 톡해 생성을 μ„ νƒμ μœΌλ‘œ μ²˜λ¦¬ν•˜λ―€λ‘œ λ‹€ν˜•μ„±μ˜ 단점을 ν•΄κ²°ν•  수 μžˆλ‹€.
λ‹€λ§Œ, μƒˆλ‘œμš΄ 객체가 μΆ”κ°€λœλ‹€λ©΄ 쑰건이 μΆ”κ°€λ˜μ–΄μ•Ό ν•˜κ³  ν™•μž₯ μ‹œ ν•˜μœ„ 클래슀의 규λͺ¨κ°€ 컀지기 λ•Œλ¬Έμ— μœ μ§€ λ³΄μˆ˜κ°€ μ–΄λ €μšΈ 수 μžˆλ‹€.


profile
μŠ΅κ΄€μ΄ μ „λΆ€λ‹€.

0개의 λŒ“κΈ€