0Pricing
Clean Architecture & Design Patterns in Practice · Ders

Uyarlayıcı ve Dekoratör Kalıpları

Uyarlayıcının uyumsuz arayüzlerin birlikte çalışmasını nasıl sağladığını ve Dekoratörün sorumlulukları dinamik olarak nasıl eklediğini anlayın.

Uyarlayıcı ve Dekoratör Kalıpları, CoddyKit'te ücretsiz bir Clean Architecture & Design Patterns in Practice dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Clean Architecture & Design Patterns in Practice öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Clean Architecture & Design Patterns in Practice kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Structural Patterns: Connect & Enhance

Welcome to Structural Design Patterns! These patterns help you compose objects and classes into larger structures, making systems more flexible and efficient.

In this lesson, we'll explore two powerful patterns:

  • Adapter Pattern: For making incompatible interfaces work together.
  • Decorator Pattern: For adding new functionalities to objects dynamically.

The Incompatibility Challenge

Imagine you have an existing system that expects objects to behave in a certain way (a specific interface). Now, you need to integrate a new component that does similar work but has a different interface.

How do you make them talk without changing the existing system or the new component? This is a common challenge in software development.

Meet the Adapter Pattern

The Adapter Pattern acts as a bridge between two incompatible interfaces. It converts the interface of one class into another interface that clients expect.

Think of a universal power adapter: it lets your device (client) plug into any wall socket (adaptee) by converting the physical connection. The device doesn't care about the socket type, only that it gets power.

Roles in the Adapter Pattern

The Adapter Pattern involves three key roles:

  • Target: The interface the client expects and uses.
  • Adaptee: The existing class with the incompatible interface that needs adapting.
  • Adapter: The class that implements the Target interface and wraps an Adaptee instance, translating client requests into calls to the Adaptee.

It allows clients to work with different classes through a single, consistent interface.

Adapter Code Example

Let's see how an adapter can make a modern console writer work with an old logging system.

Our LegacyLogger expects a logMessage method, but our ModernConsoleWriter has writeToConsole.

The ConsoleWriterAdapter bridges this gap.

interface LegacyLogger {
  void logMessage(String message);
}

class ModernConsoleWriter {
  public void writeToConsole(String text) {
    System.out.println("Console: " + text);
  }
}

class ConsoleWriterAdapter implements LegacyLogger {
  private ModernConsoleWriter adaptee;

  public ConsoleWriterAdapter(ModernConsoleWriter adaptee) {
    this.adaptee = adaptee;
  }

  @Override
  public void logMessage(String message) {
    adaptee.writeToConsole("[LEGACY] " + message);
  }
}

public class Main {
  public static void main(String[] args) {
    ModernConsoleWriter writer = new ModernConsoleWriter();
    LegacyLogger logger = new ConsoleWriterAdapter(writer);

    System.out.println("Using the adapter:");
    logger.logMessage("This is an old log entry.");

    System.out.println("\nUsing the original writer directly:");
    writer.writeToConsole("This is a modern console output.");
  }
}

When to Apply Adapter

Consider using the Adapter Pattern when:

  • You want to use an existing class, but its interface doesn't match the one you need.
  • You want to create a reusable class that cooperates with unrelated or unforeseen classes, meaning classes that don't necessarily have compatible interfaces.
  • You're integrating a new component or library into an existing system with a fixed API.

Decorator: Adding Features Dynamically

Sometimes you need to add new responsibilities or behaviors to an object without altering its original structure or affecting other objects of the same class. This is where the Decorator Pattern shines.

It allows you to wrap objects with new functionality, like adding toppings to a base coffee. Each topping (decorator) adds a new cost and description without changing the coffee itself.

Roles in the Decorator Pattern

The Decorator Pattern involves:

  • Component: The base interface for objects that can be decorated. Both concrete components and decorators implement this.
  • Concrete Component: The basic object to which responsibilities can be added.
  • Decorator: An abstract class (or interface) that maintains a reference to a Component object and implements the Component interface.
  • Concrete Decorators: Specific decorators that add new functionalities to the component.

Decorator Code Example

Let's see how to add milk and sugar to a simple coffee using decorators. Each decorator wraps the existing coffee object and adds its own logic.

This allows for flexible combinations of enhancements.

interface Coffee {
  double getCost();
  String getDescription();
}

class SimpleCoffee implements Coffee {
  @Override
  public double getCost() {
    return 2.0;
  }

  @Override
  public String getDescription() {
    return "Simple Coffee";
  }
}

abstract class CoffeeDecorator implements Coffee {
  protected Coffee decoratedCoffee;

  public CoffeeDecorator(Coffee coffee) {
    this.decoratedCoffee = coffee;
  }

  @Override
  public double getCost() {
    return decoratedCoffee.getCost();
  }

  @Override
  public String getDescription() {
    return decoratedCoffee.getDescription();
  }
}

class MilkDecorator extends CoffeeDecorator {
  public MilkDecorator(Coffee coffee) {
    super(coffee);
  }

  @Override
  public double getCost() {
    return super.getCost() + 0.5;
  }

  @Override
  public String getDescription() {
    return super.getDescription() + ", Milk";
  }
}

class SugarDecorator extends CoffeeDecorator {
  public SugarDecorator(Coffee coffee) {
    super(coffee);
  }

  @Override
  public double getCost() {
    return super.getCost() + 0.2;
  }

  @Override
  public String getDescription() {
    return super.getDescription() + ", Sugar";
  }
}

public class Main {
  public static void main(String[] args) {
    Coffee myCoffee = new SimpleCoffee();
    System.out.println(myCoffee.getDescription() + " $" + myCoffee.getCost());

    myCoffee = new MilkDecorator(myCoffee);
    System.out.println(myCoffee.getDescription() + " $" + myCoffee.getCost());

    myCoffee = new SugarDecorator(myCoffee);
    System.out.println(myCoffee.getDescription() + " $" + myCoffee.getCost());

    Coffee anotherCoffee = new SugarDecorator(new MilkDecorator(new SimpleCoffee()));
    System.out.println(anotherCoffee.getDescription() + " $" + anotherCoffee.getCost());
  }
}

When to Apply Decorator

Use the Decorator Pattern when:

  • You need to add responsibilities to individual objects dynamically and transparently, without affecting other objects.
  • You want to extend an object's functionality without using subclassing, which can lead to a "subclass explosion" for many combinations.
  • You need to allow for flexible combinations of responsibilities.

Quick Check: Pattern Purpose

Read the descriptions below. Which one correctly identifies the primary purpose of the Adapter Pattern?

Recap: Adapter & Decorator

Great job! You've now learned two powerful structural design patterns:

  • Adapter Pattern: Solves the problem of incompatible interfaces, allowing existing components to work together seamlessly. It's about 'making things fit'.
  • Decorator Pattern: Solves the problem of adding new responsibilities to objects dynamically, without altering their core structure. It's about 'enhancing functionality'.

These patterns provide flexible ways to structure your code, making it more maintainable and extensible. Keep practicing them!

Sıkça Sorulan Sorular

“Uyarlayıcı ve Dekoratör Kalıpları” dersi ücretsiz mi?

Evet — “Uyarlayıcı ve Dekoratör Kalıpları” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Clean Architecture & Design Patterns in Practice kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Clean Architecture & Design Patterns in Practice kursu toplamda 4 dersten oluşur.

“Uyarlayıcı ve Dekoratör Kalıpları” dersinde ne öğreneceğim?

Uyarlayıcının uyumsuz arayüzlerin birlikte çalışmasını nasıl sağladığını ve Dekoratörün sorumlulukları dinamik olarak nasıl eklediğini anlayın. Clean Architecture & Design Patterns in Practice ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Clean Architecture & Design Patterns in Practice öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Clean Architecture & Design Patterns in Practice, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Uyarlayıcı ve Dekoratör Kalıpları” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Clean Architecture & Design Patterns in Practice dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Clean Architecture & Design Patterns in Practice dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Uyarlayıcı ve Dekoratör Kalıpları
  2. Cephe ve Vekil Kalıpları
  3. Bileşik ve Köprü Kalıpları
  4. Bellek Verimliliği için Flyweight Kalıbı
← Clean Architecture & Design Patterns in Practice Sayfasına Dön