0Pricing
Clean Architecture & Design Patterns in Practice · Ders

Soyut Fabrika ve Oluşturucu

İlişkili nesne aileleri oluşturmak için Soyut Fabrikayı, karmaşık nesneleri adım adım oluşturmak için Oluşturucuyu keşfedin.

Soyut Fabrika ve Oluşturucu, CoddyKit'te ücretsiz bir Clean Architecture & Design Patterns in Practice dersidir. Bu, 4 dersinin 2. 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.

Patterns for Object Creation

Welcome to this lesson on two powerful creational design patterns: Abstract Factory and Builder.

These patterns help us manage the complex process of creating objects, making our code more flexible and maintainable.

You'll learn when and how to use each to build robust applications.

Abstract Factory: The Problem

Imagine you're building an application that needs to support different 'themes' or 'operating systems' (like Windows and macOS) for its UI components.

You need to create a family of related objects (buttons, checkboxes, text fields) that all belong to a specific theme.

How do you ensure you're always creating the correct set of components for a chosen theme without hardcoding them?

Abstract Factory: The Solution

The Abstract Factory pattern provides an interface for creating families of related or interdependent objects without specifying their concrete classes.

  • It defines an Abstract Factory (an interface) with methods for creating each product type (e.g., createButton(), createCheckbox()).
  • Concrete Factories implement this interface, each responsible for creating products of a specific family (e.g., WindowsUIFactory, MacUIFactory).
  • Your client code interacts only with the abstract factory and abstract products, staying independent of concrete implementations.

Abstract Factory Code: UI Kit

Let's see how an Abstract Factory can create different UI components. Here, we define interfaces for Button and Checkbox, and an UIFactory to produce them for different OS styles.

interface Button {
  void paint();
}

interface Checkbox {
  void paint();
}

class WindowsButton implements Button {
  @Override
  public void paint() {
    System.out.println("Rendered Windows Button");
  }
}

class MacButton implements Button {
  @Override
  public void paint() {
    System.out.println("Rendered Mac Button");
  }
}

class WindowsCheckbox implements Checkbox {
  @Override
  public void paint() {
    System.out.println("Rendered Windows Checkbox");
  }
}

class MacCheckbox implements Checkbox {
  @Override
  public void paint() {
    System.out.println("Rendered Mac Checkbox");
  }
}

interface UIFactory {
  Button createButton();
  Checkbox createCheckbox();
}

class WindowsUIFactory implements UIFactory {
  @Override
  public Button createButton() {
    return new WindowsButton();
  }

  @Override
  public Checkbox createCheckbox() {
    return new WindowsCheckbox();
  }
}

class MacUIFactory implements UIFactory {
  @Override
  public Button createButton() {
    return new MacButton();
  }

  @Override
  public Checkbox createCheckbox() {
    return new MacCheckbox();
  }
}

public class Main {
  public static void main(String[] args) {
    UIFactory factory;
    String os = "Mac"; // Or "Windows"

    if (os.equals("Windows")) {
      factory = new WindowsUIFactory();
    } else {
      factory = new MacUIFactory();
    }

    Button button = factory.createButton();
    Checkbox checkbox = factory.createCheckbox();

    button.paint();
    checkbox.paint();
  }
}

Builder Pattern: Complex Objects

Now, let's switch gears to the Builder pattern. Imagine you need to create a complex object, like a custom computer or a detailed report.

This object might have many optional parts, and its construction can involve a specific sequence of steps.

If you try to use a constructor with many parameters, it quickly becomes unreadable and hard to manage.

Builder Pattern: The Process

The Builder pattern separates the construction of a complex object from its representation.

  • A separate Builder object is responsible for constructing the final Product step-by-step.
  • It provides a fluent API (method chaining) to set various properties or parts of the object.
  • Finally, a build() method returns the fully constructed object.
  • This makes object creation code much cleaner and more readable, especially for objects with many optional parameters.

Builder Code: Custom Pizza!

Let's use the Builder pattern to create a custom Pizza. We can specify the crust, sauce, cheese, and toppings step-by-step, making the creation process clear.

class Pizza {
  private String crust;
  private String sauce;
  private String cheese;
  private String toppings;

  public Pizza(String crust, String sauce, String cheese, String toppings) {
    this.crust = crust;
    this.sauce = sauce;
    this.cheese = cheese;
    this.toppings = toppings;
  }

  @Override
  public String toString() {
    return "Pizza with: " + crust + " crust, " + sauce + " sauce, " + cheese + " cheese, " + toppings + ".";
  }
}

class PizzaBuilder {
  private String crust = "thin";
  private String sauce = "tomato";
  private String cheese = "mozzarella";
  private String toppings = "none";

  public PizzaBuilder withCrust(String crust) {
    this.crust = crust;
    return this;
  }

  public PizzaBuilder withSauce(String sauce) {
    this.sauce = sauce;
    return this;
  }

  public PizzaBuilder withCheese(String cheese) {
    this.cheese = cheese;
    return this;
  }

  public PizzaBuilder withToppings(String toppings) {
    this.toppings = toppings;
    return this;
  }

  public Pizza build() {
    return new Pizza(crust, sauce, cheese, toppings);
  }
}

public class Main {
  public static void main(String[] args) {
    Pizza margherita = new PizzaBuilder()
      .withCrust("classic")
      .withSauce("tomato")
      .withCheese("mozzarella")
      .build();
    System.out.println(margherita);

    Pizza veggieDelight = new PizzaBuilder()
      .withCrust("whole wheat")
      .withSauce("pesto")
      .withCheese("feta")
      .withToppings("onions, peppers, olives")
      .build();
    System.out.println(veggieDelight);
  }
}

Patterns Compared

While both patterns deal with object creation, they solve different problems:

  • Abstract Factory: Focuses on creating families of related objects. It provides a way to encapsulate a group of individual factories that have a common theme without exposing the concrete classes.
  • Builder: Focuses on creating a single complex object step-by-step. It's ideal when an object has many parameters, some optional, and its construction involves a multi-stage process.

Abstract Factory returns a factory, Builder returns the product itself.

Practical Applications

You'll find these patterns in many real-world scenarios:

  • Abstract Factory: Database connection factories (e.g., creating specific connection objects for MySQL, PostgreSQL, Oracle), cross-platform UI toolkits, or creating different configurations of a system.
  • Builder: Constructing complex SQL queries, generating reports with many customizable sections, configuring HTTP requests, or creating complex data transfer objects (DTOs).

They bring clarity and flexibility to object instantiation.

Quick Check

Consider the problems below. Which of them are typically best solved using the Abstract Factory pattern?

Abstract Factory & Builder Recap

Great job! In this lesson, you explored two powerful creational patterns:

  • Abstract Factory: Best for creating families of related objects, ensuring consistency across different implementations.
  • Builder: Perfect for constructing complex objects step-by-step, especially when they have many optional parts, making the creation process clear and manageable.

These patterns are crucial tools for designing flexible and maintainable software systems.

Sıkça Sorulan Sorular

“Soyut Fabrika ve Oluşturucu” dersi ücretsiz mi?

Evet — “Soyut Fabrika ve Oluşturucu” 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.

“Soyut Fabrika ve Oluşturucu” dersinde ne öğreneceğim?

İlişkili nesne aileleri oluşturmak için Soyut Fabrikayı, karmaşık nesneleri adım adım oluşturmak için Oluşturucuyu keşfedin. 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 2. dersidir.

“Soyut Fabrika ve Oluşturucu” 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. Tekil ve Fabrika Metodu
  2. Soyut Fabrika ve Oluşturucu
  3. Prototip ve Nesne Havuzu
  4. Nesne Oluşturma Tekniği Olarak Bağımlılık Enjeksiyonu
← Clean Architecture & Design Patterns in Practice Sayfasına Dön