11-04 20:20
- Today
 
- Total
 
													Link
													
												
											
												
												
											
									개발하는 고라니
[Java] 하나의 객체로 Singleton 패턴 적용 본문
반응형
    
    
    
  Spring을 사용해보았다면 필요한 객체를 주입받는 @Autowired 어노테이션을 알 것이다. 이는 어플리케이션 전체에 공유되는 하나의 객체를 Spring IoC 컨테이너에서 주입받아 사용하는 것인데, 이는 Singleton 패턴이라고 한다.
Spring의 @Autowired를 사용하지 않고 모든 곳에서 공통으로 사용될 수 있는 하나의 객체를 만들어보자.
내용
- 3개의 컨트롤러와 3개의 View가 필요하다.
- AController, BController, CController
 - /a/index.html, /b/index.html, /c/index.html
 
 - 전역에서 쓰일 객체 SimpleStorage
- private Map<String, List<String>> map을 멤버로 갖는다.
 - map은 key('a', 'b', 'c')로 value(List<String>)를 갖는 Map이다.
 
 - 각 뷰페이지는 'a'로 매핑된 List<String>, 'b'로 매핑된 List<String> 'c'로 매핑된 List<String>에서 데이터를 가져온다.
 
Controller
//AController KEY = 'a' return "a/index";
//BController KEY = 'b' return "b/index";
//CController KEY = 'c' return "c/index";
@Controller
@RequestMapping("/a")
public class AController {
    private static SimpleStorage storage = SimpleStorage.getInstance();
    private static final String KEY = "a";
    private List<String> list;
    @PostConstruct
    public void init(){
        try {
            this.list = storage.getList(KEY);
            list.forEach(System.out::println);
            System.out.println("Key 'A' 받았습니다~");
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    @GetMapping("/index")
    public String index(Model model){
        model.addAttribute("list", list);
        return "a/index";
    }
    @PostMapping("/index")
    public String postIndex(String value){
        list.add(value);
        return "redirect:/a/index";
    }
}
View
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>A.index</h1>
<form method="post">
    <input type="text" name="value">
    <input type="submit" value="send">
</form>
<div th:each="data : ${list}">
    <div th:text="${data}"></div>
    <br>
</div>
<a href="/a/index">to A</a>
<a href="/b/index">to B</a>
<a href="/c/index">to C</a>
</body>
</html>
SimpleStorage
public class SimpleStorage {
    private static SimpleStorage instance;
    private Map<String, List<String>> map;
    //생성자를 은닉화함으로써 메서드를 통해 객체를 주입받는다.
    private SimpleStorage(){
        System.out.println("===================SimpleStorage Created!!=====================");
        map = new HashMap<>();
    }
    //SimpleStorage 객체를 주입받는 메서드 (생성자 대용)
    public static synchronized SimpleStorage getInstance(){
        if(instance == null)
            instance = new SimpleStorage();
        return instance;
    }
    //key를 받아 해당 key로 매핑된 list를 반환,
    //list를 갖고있지 않다면 새로 생성해서 put() 후 반환
    public List<String> getList(String key){
        if(map.containsKey(key))
            return map.get(key);
        else {
            List<String> list = new ArrayList<>();
            map.put(key, list);
            return list;
        }
    }
}
Result



반응형
    
    
    
  'Languages > Java' 카테고리의 다른 글
| [Java] 추상화 (0) | 2021.04.05 | 
|---|---|
| [Java] 파일 입력과 EOF (0) | 2021.03.10 | 
| [Java] Shuffle 메서드 (0) | 2021.03.10 | 
| [Java] 상속 (0) | 2021.03.08 | 
| [Java] 클래스와 객체 (0) | 2021.03.01 | 
			  Comments