Skip to content

Latest commit

 

History

History
122 lines (93 loc) · 3.41 KB

File metadata and controls

122 lines (93 loc) · 3.41 KB

2021.11.21_04.자바와스프링에서찾아보는패턴

추상팩토리 패턴 실무에서 사용

public class DocumentBuilderFactoryExample{
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("src/main/resources/config.xml"));
        System.out.println(document.getDocumentElement());
    }
}
  • DocumentBuilderFactory 자바 x 파서에 있음

  • 이 자체가 추상팩토리라고 볼 수 있음

  • DocumentBuilder의 추상적인 메소드를 통해서 작업만 하면됨

    • 초점을 클라이언트 입장에두는 것
  • 자바의 라이브러리에서는

    • javax.xml.xpath.XPathFactory#newInstance()
    • javax.xml.transform.TransformerFactory#newInstance()
    • javax.xml.parsers.DocumentBuilderFactory#newInstance()
  • 스프링

    • FactoryBean과 그 구현체
    • 스프링이 제공하는 인터페이스
  • new로는 만들 수 없고 복잡한 과정을 거칠때 함

<bean id ="hello" class ="java.lang.String">
    <constructor-arg value="hello"/>
</bean>
  • 이렇게 쉽게 만들 수 있었는데
  • 팩토리 빈을 쓰는 경우 만드는 법이 복잡한 경우는 팩토리빈을 직접 구현해서 사용
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 Ship.class;}
}
  • 이 클래스를 빈으로 등록하면 이 팩토리가 빈으로 등록되서 가능하게됨

    • public interface FactoryBean의 경우는 추상팩토리인터페이스에 해당
    • 위의 구현해서 제공한 것은 추상적인 팩토리 인터페이스의 구현체가 되는 것
  • 클라이언트에서 사용하는 것은 스프링 내부에 존재함

사용하기

config.xml

<bean id = "whiteship" class="ShipFactory"/>
  • 빈에 등록을 함

  • 실제로 가져올때는 ship으로 가져올 수 있음

public class FactoryExample{
    public static void main(String[] args){
		ApplicationContext applicationContext = new ClasPathApplicationContext("config.xml");
        Ship whiteship = applicationContext.getBean("whiteship",Ship.class);
        System.out.println(whiteship.getName());
    }
}
  • ShipFactory로 등록했지만 Ship으로 가져옴

자바설정 빈 만들기

public class FactoryBeanConfig{
    @Bean
    public ShipFactory shipFactory(){
        return new ShipFactory();
    }
}

자바로 설정시 두가지 방법 사용

public class FactoryExample{
    public static void main(String[] args){
		ApplicationContext applicationContext = new ClasPathApplicationContext(FactoryBeanConfig.class);
        ShipFactory bean = applicationContext.getBean(ShipFactory.class);
        System.out.println(bean);
    }
}
public class FactoryExample{
    public static void main(String[] args){
		ApplicationContext applicationContext = new ClasPathApplicationContext(FactoryBeanConfig.class);
        Ship bean = applicationContext.getBean(Ship.class);
        System.out.println(bean);
    }
}
  • ShipFactory 또는 Ship으로 가져올 수 있음