본문 바로가기

programming

(23)
Item 2. 생성자에 매개변수가 많다면 빌더를 고려하라 방법 1 점층적 생성자 패턴 public class Member { private String name; // 필수 private int age; // 필수 private String address; // 선택 private String phone; // 선택 private String email; // 선택 // 필수 매개변수를 가지는 생성자 public Member(String name, int age) { this(name, age, null, null, null); } // 선택 매개변수 address가 추가된 생성자 public Member(String name, int age, String address) { this(name, age, address, null, null); } // 선택 매..
Item1. 생성자 대신 정적 팩터리 메서드를 고려하라. 정적 팩토리 메서드 장단점 장점 이름을 가질 수 있다. 메서드의 이름으로 생성한 객체의 특성이나 역할을 코드 상에서 쉽게 유추할 수 있다. → 가독성 up 호출될 때마다 인스턴스를 새로 생성하지 않아도 된다. Boolean 클래스에서 TRUE, FALSE 두가지 상태 인스턴스 불변 클래스 싱글턴 방식 생성된 인스턴스를 재사용하는 것이 가능한 경우에는 불필요하게 인스턴스를 새로 생성하지 않고 정적 팩토리 메서드를 이용한 재사용 인스턴스를 이용하는 것이 좋다. 플라이웨이트 패턴 반환 타입의 하위 타입 객체를 반환할 수 있는 능력이 있다. 부모 클래스(혹은 인터페이스)를 구현한 자식 클래스가 있다면 자식 클래스를 반환타입으로 사용할 수 있다. 인터페이스의 요소들만 알아도, 그 구현체들에 대한 이름조차 몰라도 ..
[파일 시스템] 파일 삭제 코드 디렉터리에 저장된 파일을 모두 삭제하고 싶을 때 사용할 수 있는 코드다. public static void deleteDirectory(File directory) { // Get a list of all the files in the directory File[] files = directory.listFiles(); // If the directory is not empty, delete its contents if (files != null) { for (File file : files) { // If the file is a directory, recursively delete its contents if (file.isDirectory()) { deleteDirectory(file); } // ..
thread 동기화 방법 case 1 : 그냥 공유 변수를 사용할 때 class Ex1{ static class Memory { private int var; public int getVar() { return var; } public void setVar(int var) { this.var = var;} } void ThreadConflict() throws InterruptedException { //공유 변수 클래스 Memory memory = new Memory(); //Thread 동작 Runnable logic = () -> { for(int i = 0; i< 10000; i++) { int var = memory.getVar(); memory.setVar(++var); } }; //Thread 생성 Thread A ..
SOLID 객체 지향 설계의 5가지 원칙 SOLID 더보기 SRP : 단일 책임 원칙 (single responsibility principle) OCP : 개방 폐쇄 원칙 (Open/Closed principle) LSP : 리스코프 치환 원칙 (Liskov substitution principle) ISP : 인터페이스 분리 원칙 (Interface segregation principle) DIP : 의존 관계 역전 원칙 (Dependency inversion principle) 1. SRP 단일 책임 원칙 - 한 클래스는 하나의 책임만 가져야 한다. - 변경이 있을 때 파급 효과가 적으면 단일 책임 원칙을 잘 따른 것 2. OCP 개방 폐쇄 원칙 - 소프트웨어 요소는 확장에는 열려 있으나 변경에는 닫혀 있어야..
HashTable HashTable 사용법 1. Hashtable 생성 Hashtable ht = new Hashtable() Hashtable ht = new Hashtable(int capacity); Hashtable ht = new Hashtable(int capacity, float loadFactor); Hashtable ht = new Hashtable(map t); 2. 값 추가 ht.put(0, "test0"); ht.put(1, "test1"); 3. 값 삭제 ht.remove(2);//2번 키를 가지는 데이터 삭제 4. 값 변경 ht.replace(0, "test00"); 5. 값 가져오기 ht.get(key); 6. 크기 구하기 ht.size(); 7. 검색 ht.containsKey(key); ht..
HashSet HashSet - Set 인터페이스의 구현 클래스 - 객체를 중복해서 저장할 수 없음 - 저장 순서가 불규칙 1. 선언 HashSet set1 = new HashSet(); HashSet set2 = new HashSet(); HashSet set3 = new HashSet(set1);//set1을 복사 HashSet set4 = new HashSet(int capacity); HashSet set5 = new HashSet(int capacity, float load factor); HashSet set6 = new HashSet(Arrays.asList(1,2,3));//초기값 지정 +적재율(load factor)이란 해시 테이블의 크기 대비, 키의 개수를 말한다. 즉, 키의 개수를 K, 해시 테이블..