Specification ํจํด์ ๋๋ฉ์ธ ๊ฐ์ฒด์ ๋ํ ์กฐ๊ฑด์ด๋ ๊ท์น์ ์บก์ํํ์ฌ ์ฌ์ฌ์ฉ ๋ฐ ์กฐํฉ ๊ฐ๋ฅํ ํํ๋ก ํํํ๋ ๋์์ธ ํจํด์
๋๋ค.
์ฆ, ๋น์ฆ๋์ค ๊ท์น์ด๋ ์กฐ๊ฑด์ ๋ณ๋์ ๊ฐ์ฒด(์คํ)๋ก ๋ถ๋ฆฌํ์ฌ, ์ฌ๋ฌ ๊ณณ์์ ์ฌ์ฌ์ฉํ๊ฑฐ๋ ๋ณตํฉ์ ์ธ ์กฐ๊ฑด์ ๊ตฌ์ฑํ ์ ์๊ฒ ํด์ค๋๋ค.
How do Codeโ
public interface Specification<T> {
boolean isSatisfiedBy(T candidate);
default Specification<T> and(Specification<T> other) {
return candidate -> this.isSatisfiedBy(candidate) && other.isSatisfiedBy(candidate);
}
default Specification<T> or(Specification<T> other) {
return candidate -> this.isSatisfiedBy(candidate) || other.isSatisfiedBy(candidate);
}
default Specification<T> not() {
return candidate -> !this.isSatisfiedBy(candidate);
}
}
public class Product {
private String name;
private double price;
private boolean inStock;
public Product(String name, double price, boolean inStock) {
this.name = name;
this.price = price;
this.inStock = inStock;
}
// Getter ๋ฉ์๋๋ค
public String getName() { return name; }
public double getPrice() { return price; }
public boolean isInStock() { return inStock; }
}
public class PriceSpecification implements Specification<Product> {
private double minPrice;
private double maxPrice;
public PriceSpecification(double minPrice, double maxPrice) {
this.minPrice = minPrice;
this.maxPrice = maxPrice;
}
@Override
public boolean isSatisfiedBy(Product candidate) {
return candidate.getPrice() >= minPrice && candidate.getPrice() <= maxPrice;
}
}
interface Specification<T> {
fun isSatisfiedBy(candidate: T): Boolean
infix fun and(other: Specification<T>): Specification<T> = object : Specification<T> {
override fun isSatisfiedBy(candidate: T): Boolean =
this@Specification.isSatisfiedBy(candidate) && other.isSatisfiedBy(candidate)
}
infix fun or(other: Specification<T>): Specification<T> = object : Specification<T> {
override fun isSatisfiedBy(candidate: T): Boolean =
this@Specification.isSatisfiedBy(candidate) || other.isSatisfiedBy(candidate)
}
operator fun not(): Specification<T> = object : Specification<T> {
override fun isSatisfiedBy(candidate: T): Boolean =
!this@Specification.isSatisfiedBy(candidate)
}
}
// Product.kt
data class Product(
val name: String,
val price: Double,
val inStock: Boolean
)
class PriceSpecification(private val minPrice: Double, private val maxPrice: Double) : Specification<Product> {
override fun isSatisfiedBy(candidate: Product): Boolean {
return candidate.price in minPrice..maxPrice
}
}