package 정적팩토리메서드패턴;
public class Book {
private Book() {}
public static Book of(){
return new Book();
}
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
Book book = Book.of();
}
}
package 정적팩토리메서드패턴;
public class Car {
private String brand;
private String color = "black";
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
}
public Car(String brand) {
this.brand = brand;
}
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
Car car1 = new Car("테스트 브랜드1");
Car car2 = new Car("테스트 브랜드1","blue");
}
}
package 정적팩토리메서드패턴;
public class Car {
private String brand;
private String color = "black";
// 생성자 숨기기
private Car() {}
// 생성자 숨기기
private Car(String brand, String color) {
this.brand = brand;
this.color = color;
}
// 매개 변수 하나는 from 네이밍
public static Car brandFrom(String brand){
return new Car(brand,"black");
}
// 매개변수 2개이상은 of 네이밍
public static Car brandColorFrom(String brand, String color){
return new Car(brand,color);
}
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
Car car1 = Car.brandFrom("테스트 브랜드1");
Car car2 = Car.brandColorFrom("테스트 브랜드1","blue");
}
}
package 정적팩토리메서드패턴;
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if ( instance == null ) {
instance = new Singleton();
}
return instance;
}
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1.hashCode());
System.out.println(singleton2.hashCode());
}
}
package 정적팩토리메서드패턴;
class Galaxy implements SmartPhone {}
class IPhone implements SmartPhone {}
class Huawei implements SmartPhone {}
public interface SmartPhone {
static Galaxy getGalaxy(){
return new Galaxy();
}
static SmartPhone getApplePhone() {
return new IPhone();
}
static SmartPhone getChinesePhone() {
return new Huawei();
}
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
SmartPhone galaxy = SmartPhone.getGalaxy();
SmartPhone iPhone = SmartPhone.getApplePhone();
SmartPhone huawei = SmartPhone.getChinesePhone();
}
}
static SmartPhone getRandomPhone(){
int price = 10000;
if (price >= 5000) {
new Galaxy();
} else if (price >= 7000) {
new IPhone();
} else {
new Huawei();
}
return null;
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
SmartPhone galaxy = SmartPhone.getRandomPhone();
}
}
package 정적팩토리메서드패턴;
public class Main {
public static void main(String[] args) {
Integer i1 = Integer.valueOf(100);
Integer i2 = Integer.valueOf(100);
System.out.println(i1 == i2);
Integer i3 = Integer.valueOf(128);
Integer i4 = Integer.valueOf(128);
System.out.println(i3 == i4);
}
}