Created
November 19, 2018 02:12
-
-
Save minikuma/b6cc00bcea574ff828126ed41ca11fa3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************************** | |
Item01 장점3> 해당 객체의 하위 타입을 리턴할 수 있다. | |
Item01 장점4> 리턴하는 객체의 클래스가 입력 매개변수에 따라 다른 리턴값을 갖게 할 수 있다. | |
*************************************************************/ | |
public class Drill { | |
private String id; | |
private int num; | |
public Drill() { } | |
// 장점 2 > Instance cache, immutable object | |
private static final Drill CACHE = new Drill(); | |
public Drill(String id) { | |
this.id = id; | |
} | |
public Drill(int num) { | |
this.num = num; | |
} | |
// 장점 1 > naming | |
public static Drill withId(String id) { | |
Drill d = new Drill(); | |
d.id = id; | |
return d; | |
} | |
public static Drill withNum(int num) { | |
return new Drill(num); | |
} | |
// 장점 2 > Instance cache, immutable object | |
public static Drill getInstance(boolean flag) { | |
return flag ? new Drill() : new BarDrill(); | |
} | |
// Drill의 하위 Type Class인 BarDrill | |
static class BarDrill extends Drill { | |
} | |
//client 소스에서 사용 | |
public static void main(String[] args) { | |
// as-is 방식 (new) | |
Drill d = new Drill("minikuma"); | |
//장점 1 > static method | |
Drill d1 = withId("minikuma"); | |
//장점 3, 4 > cach, immutable object | |
Drill d2 = getInstance(false); | |
System.out.println("d -> " + d); | |
System.out.println("d1 -> " + d1); | |
System.out.println("d2 -> " + d2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment