2023. 3. 2. 16:24γJAVA/Effective JAVA
item18. μμ보λ€λ μ»΄ν¬μ§μ μ μ¬μ©νλΌ.
" p.119 λ°μ½λ μ΄ν° ν¨ν΄"
[μ΄νν°λΈ μλ°] Item18. μμ보λ€λ μ»΄ν¬μ§μ μ μ¬μ©νλΌ. (tistory.com)
λ°μ½λ μ΄ν° ν¨ν΄ Decorator Pattern μ΄λ?
: κΈ°μ‘΄ μ½λλ₯Ό λ³κ²½νμ§ μκ³ λΆκ° κΈ°λ₯μ μΆκ°νλ ν¨ν΄, κ°μ²΄μ κ²°ν©μ ν΅ν΄ κΈ°λ₯μ λμ μΌλ‘ μ μ°νκ² νμ₯ν μ μκ² ν΄μ£Όλ ν¨ν΄μ΄λ€.
λ°μ½λ μ΄ν° ν¨ν΄μ μμμ΄ μλ μμμ μ¬μ©ν΄μ λ³΄λ€ μ μ°νκ²(λμ μΌλ‘, λ°νμμ) λΆκ° κΈ°λ₯μ μΆκ°νλ κ²λ κ°λ₯νλ€.
Component
: κΈ°λ³Έ κΈ°λ₯
ConcreateComponent
: κΈ°λ³Έ κΈ°λ₯μ ꡬννλ ν΄λμ€
Decorator
: λ§μ μκ° μ‘΄μ¬νλ ꡬ체μ μΈ Decoratorμ κ³΅ν΅ κΈ°λ₯μ μ μ
ConcreateDecorator1, ConcreateDecorator2
: Decoratorμ νμ ν΄λμ€λ‘, κΈ°λ³Έ κΈ°λ₯μ μΆκ°λλ κ°λ³μ μΈ κΈ°λ₯μ λ»νλ€.
public class ForwardingSet<E> implements Set<E>
{
private final Set<E> s;
public ForwardingSet(Set<E> s)
{
this.s = s;
}
public void clear()
{
s.clear();
}
public boolean contains(Object o)
{
return s.contains(o);
}
public boolean isEmpty()
{
return s.isEmpty();
}
public int size()
{
return s.size();
}
public Iterator<E> iterator()
{
return s.iterator();
}
public boolean add(E e)
{
return s.add(e);
}
public boolean remove(Object o)
{
return s.remove(o);
}
public boolean containsAll(Collection<?> collection)
{
return s.containsAll(collection);
}
public boolean addAll(Collection<? extends E> collection)
{
return s.addAll(collection);
}
public boolean removeAll(Collection<?> c)
{
return s.removeAll(c);
}
public boolean retainAll(Collection<?> collection)
{
return s.retainAll(collection);
}
public Object[] toArray()
{
return s.toArray();
}
public <T> T[] toArray(T[] a)
{
return s.toArray(a);
}
}
public class InstrumentedSet<E> extends ForwardingSet<E>
{
private int addCount = 0;
public InstrumentedSet(Set<E> s)
{
super(s);
}
@Override
public boolean add(E e)
{
addCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> collection)
{
addCount += collection.size();
return super.addAll(collection);
}
public int getAddCount()
{
return addCount;
}
public static void main(String[] args)
{
InstrumentedSet<String> s = new InstrumentedSet<>(new HashSet<>());
s.addAll(List.of("ν±", "νν", "ν"));
System.out.println("s.getAddCount() = " + s.getAddCount());
}
}
InstrumentedSet, ForwardingSet, Set, HashSetμ ν΅ν΄ λ°μ½λ μ΄ν° ν¨ν΄μ λ³Έλ€λ©΄ μ°μ
Setμ΄ Componentμ ν΄λΉνκ³ , HashSetμ μ΄λ₯Ό ꡬνν ConcreateComponentμ ν΄λΉνλ€.
κ·Έλ¦¬κ³ Componentμ λΆκ° κΈ°λ₯μ μΆκ°νκ³ ForwardingSetμ΄ Decoratorμ ν΄λΉνλ©°, μ΄λ₯Ό Decoratorμ νμ ν΄λμ€λ‘ μ¬κΈ°μ λΆκ° κΈ°λ₯μ μΆκ°ν ConcreateDecoratorκ° InstrumentedSetμ΄ λλ€.