headfirst designPattern ์ ์ฐธ๊ณ ํ๊ณ ํ์ตํ์์ต๋๋ค.
์๋ ๋ธ๋ก๊ทธ & ๊นํ์ ์ฐธ๊ณ ํ์์ต๋๋ค.
quanke/design-pattern-java-source-code
https://github.com/bo-yoon/DesignPattern
ํด๊ฒฐ์ฑ
package singleton;
public class Refrigerator {
// ๋์ฅ๊ณ ๋ ๊ณตํต ์์
private static Refrigerator ref = null;
private Refrigerator() {} // ์์ฑ์๊ฐ private
public static Refrigerator getInstance() {
if(ref == null) {
ref = new Refrigerator();
}
return ref;
}
public void display() {
System.out.println("๋์ฅ๊ณ ๊ณต์ ");
}
}
package singleton;
public class EagerRefrigerator {
// ๋์ฅ๊ณ ๋ ๊ณตํต ์์
private static EagerRefrigerator ref = new EagerRefrigerator();
private EagerRefrigerator() {} // ์์ฑ์๊ฐ private
public static EagerRefrigerator getInstance() {
return ref;
}
public void display() {
System.out.println("Eager ๋์ฅ๊ณ ๊ณต์ ");
}
}
package singleton;
public class SyncRefrigerator {
// ๋์ฅ๊ณ ๋ ๊ณตํต ์์
private static SyncRefrigerator ref = null;
private SyncRefrigerator() {} // ์์ฑ์๊ฐ private
public synchronized static SyncRefrigerator getInstance() {
if(ref == null) {
ref = new SyncRefrigerator();
}
return ref;
}
public void display() {
System.out.println("Sync ๋์ฅ๊ณ ๊ณต์ ");
}
}
์ฆ, ์ด๋ค ์ฌ์ฉ์๊ฐ ์ํํ๋ ํ์๋ฅผ ์ฝ๊ฒ ๋ฐ๊พธ๊ฒ ํด์ค๋ค.
๋จ์ : ์ค๋ณต๋๋ ์ฝ๋ ๋ฐ์
package strategy;
public interface Exercise {
public void acting(int hours);
}
package strategy;
public class Climbing implements Exercise {
private String place; // ์ฅ์
public Climbing(String place) {
this.place = place;
}
@Override
public void acting(int hours) {
System.out.println(place + "์์ " +hours + "์๊ฐ ๋์ ํด๋ผ์ด๋ฐํจ " );
}
}
package strategy;
public class Swimming implements Exercise {
private String place;
private String things;
public Swimming(String place, String things) {
this.place = place;
this.things = things;
}
@Override
public void acting(int hours) {
System.out.println(hours +"์๊ฐ ๋์ " + place + "์์ " +things +
"์ ๊ฐ์ง๊ณ ์์");
}
}
package strategy;
public class Swimming implements Exercise {
private String place;
private String things;
public Swimming(String place, String things) {
this.place = place;
this.things = things;
}
@Override
public void acting(int hours) {
System.out.println(hours +"์๊ฐ ๋์ " + place + "์์ " +things +
"์ ๊ฐ์ง๊ณ ์์");
}
}
package strategy;
public class Child extends User {
@Override
public void display() {
System.out.println("๋๋ ์ด๋ฆฐ์ด");
}
}
package strategy;
public class Player extends User{
@Override
public void display() {
System.out.println("๋๋ ์์์ ์!");
}
}
package strategy;
public class Main {
public static void main(String [] args) {
User user = new Child(); // ํ์ ์ฌ์ฉ์ ์ ์ธ
user.display();
user.setExercise(new Swimming("์ผ๋ฆฌ๋น์๋ฒ ์ด","ํ๋ธ"));
user.doAct(5);
user.setExercise(new Climbing("์ค๋ด ์ฒด์ก๊ด"));
user.doAct(2);
}
}