Implementing Structural Design Patterns

1. Implementing Adapter Pattern

Example: Adapt incompatible interface

interface PaymentGateway { Receipt charge(Money m); }
class StripeAdapter implements PaymentGateway {
    private final StripeClient stripe;
    public Receipt charge(Money m) {
        var resp = stripe.createCharge(m.cents(), m.currency().code());
        return new Receipt(resp.id(), resp.status());
    }
}

2. Implementing Bridge Pattern

ElementRole
AbstractionRefined behavior
ImplementorPluggable backend
GoalVary abstraction & implementation independently

Example: Notification × Channel

interface Channel { void send(String to, String body); }
abstract class Notification {
    protected final Channel channel;
    Notification(Channel c) { this.channel = c; }
    abstract void notify(User u);
}
class WelcomeNotification extends Notification { ... }  // ↔ EmailChannel, SmsChannel

3. Implementing Composite Pattern

Example: Tree of components

interface FsNode { long size(); }
record File(String name, long size) implements FsNode {}
record Folder(String name, List<FsNode> children) implements FsNode {
    public long size() { return children.stream().mapToLong(FsNode::size).sum(); }
}

4. Implementing Decorator Pattern

Example: Wrap and add behavior

interface DataSource { String read(); void write(String s); }
class EncryptedDataSource implements DataSource {
    private final DataSource inner;
    EncryptedDataSource(DataSource d) { this.inner = d; }
    public String read() { return decrypt(inner.read()); }
    public void write(String s) { inner.write(encrypt(s)); }
}
DataSource ds = new EncryptedDataSource(new CompressedDataSource(new FileDataSource("a.dat")));

5. Implementing Facade Pattern

ElementRole
FacadeUnified high-level API
SubsystemHidden complex parts
GoalSimplify client interaction

Example: Order facade

class CheckoutFacade {
    public Receipt checkout(Cart c) {
        inventory.reserve(c);
        var charge = payment.charge(c.total());
        var order = orders.place(c, charge);
        notifier.confirm(order);
        return order.receipt();
    }
}

6. Implementing Flyweight Pattern

ConceptDetail
Intrinsic stateShared, immutable
Extrinsic statePassed in per use
Java examplesInteger.valueOf cache, String intern

7. Implementing Proxy Pattern

VariantUse
VirtualLazy creation of expensive object
ProtectionAccess control checks
RemoteWraps RPC stub
Smart referenceLogging, ref counting

8. Implementing Repository Pattern

Example: Domain-owned port

public interface OrderRepository {
    Optional<Order> findById(OrderId id);
    void save(Order order);
    List<Order> findByCustomer(CustomerId c, Pageable p);
}

9. Implementing Data Mapper Pattern

AspectDetail
GoalDecouple domain from persistence schema
MechanismMapper class converts entity ↔ row/document
ToolsJPA @Entity, MapStruct, jOOQ

10. Implementing Active Record Pattern

TraitDetail
Object = rowCarries data + persistence
Methodssave(), delete() on entity
ExamplesRails AR, Eloquent
Trade-offQuick start, but mixes concerns

11. Implementing Unit of Work Pattern

ElementRole
TrackingNew, dirty, removed entities
CommitSingle transaction flush
JavaJPA EntityManager per request

12. Implementing Module Pattern

LangMechanism
JSIIFE / ES modules
JavaPackage-private + module-info

13. Implementing Delegation Pattern

Example: Forward to inner

class LoggingList<T> implements List<T> {
    private final List<T> delegate;
    public boolean add(T t) { log.info("add {}", t); return delegate.add(t); }
    // ... forward all other methods
}

14. Understanding Wrapper Pattern

Wrapper TypeIntent
DecoratorAdd behavior
AdapterChange interface
ProxyControl access
FacadeSimplify subsystem

15. Implementing Private Class Data Pattern

IdeaDetail
Extract dataMove fields to inner data class
Restrict mutationSet once via constructor
Java equivalentFinal field referencing record

16. Understanding Adapter vs Decorator vs Proxy

PatternInterfaceBehavior
AdapterDifferent from wrappedTranslation
DecoratorSameAdds responsibility
ProxySameControls access

17. Creating Lazy Initialization Proxy

Example: Virtual proxy

class LazyImageProxy implements Image {
    private final String path;
    private RealImage real;
    public void render() {
        if (real == null) real = new RealImage(path);
        real.render();
    }
}

18. Implementing Virtual Proxy

WhenDetail
Heavy objectDefer until needed
Network callAvoid until first use
FrameworksHibernate lazy-loaded entities

19. Using java.lang.reflect.Proxy

Example: Dynamic proxy

MyService proxy = (MyService) Proxy.newProxyInstance(
    MyService.class.getClassLoader(),
    new Class<?>[]{MyService.class},
    (p, method, args) -> {
        log.info("call {}", method.getName());
        return method.invoke(target, args);
    });

20. Using Class Delegation

LangMechanism
Kotlinclass A(b: B): I by b
JavaManual forwarding methods

21. Using Embedding for Delegation

LangMechanism
GoEmbed struct: type A struct { B }
Java equivalentInheritance or explicit delegation

22. Using Extension Methods

LangMechanism
Kotlin/C#fun String.lastChar() = ...
JavaStatic utility methods

23. Using Extension Methods as Decorators

IdiomDetail
Wrap resultfun List<T>.cached() = MemoList(this)
Java altStatic decorator factory

24. Using Module Mixins for Decoration

LangMechanism
Rubyprepend Module
JavaDefault methods on interfaces

25. Using SimpleDelegator and DelegateClass

LangMechanism
Rubyrequire 'delegate'; class X < SimpleDelegator
JavaManual forwarding or dynamic proxy