장점 : 구체적인 클래스로부터 클라이언트를 분리할 수 있다
비슷한 객체들을 쉽게 대체할 수 있다.
사용자는 인터페이스에 대해서만 알고 있으면 사용하기 쉽다.
단점 : Product 수정 시에 Factory 구현을 변경해야 하기 때문에 Ocp를 위반할 수 있다.
public class WhiteShipFactory implements ShipFactory {
private ShipPartsFactory shipPartsFactory;
public WhiteShipFactory(ShipPartsFactory shipPartsFactory) { //shipPartsFactory를 DI해줌
this.shipPartsFactory = shipPartsFactory;
}
@Override
public Ship createShip() {
Ship ship = new WhiteShip();
ship.setAnchor(shipPartsFactory.createAnchor());
ship.setWheel(shipPartsFactory.createWheel());
return ship;
}
}
public class WhiteShipPartsFactory implements ShipPartsFactory {
@Override
public Anchor createAnchor() {
return new WhiteAnchor();
}
@Override
public Wheel createWheel() {
return new WhiteWheel();
}
}
public class WhiteProWheel implements Wheel {
}
public class WhiteProAnchor implements Anchor {
}
public class ShipFactory implements FactoryBean<Ship> {
@Override
public Ship getObject() throws Exception {
Ship ship = new WhiteShip();
ship.setName("whiteShip");
return ship;
}
@Override
public Class<?> getObjectType() {
return null;
}
}
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml");
Ship whiteShip = applicationContext.getBean("whiteShip", Ship.class);
<bean id="whiteShip" class="abstract_factory.apply.ShipFactory">
</bean>
출처 : 백기선님의 디자인패턴