รูปแบบ Composite และ Bridge
ทำงานกับ Composite สำหรับโครงสร้างแบบต้นไม้ และ Bridge เพื่อแยกส่วนสิ่งนามธรรมออกจากการใช้งานจริง
รูปแบบ Composite และ Bridge เป็นบทเรียน Clean Architecture & Design Patterns in Practice ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Clean Architecture & Design Patterns in Practice และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Composite: Grouping Objects
Imagine you're building a system where individual objects and groups of objects need to be treated uniformly. This is where the Composite pattern shines!
It lets you compose objects into tree structures to represent part-whole hierarchies. This way, clients can treat individual objects and compositions of objects uniformly.
Components, Leaves, & Composites
The Composite pattern involves three main roles:
- Component: The common interface or abstract class for both individual objects (leaves) and composite objects.
- Leaf: Represents individual objects that don't have children.
- Composite: Represents objects that can have children (other Components). It manages child components and delegates operations to them.
Composite in Action: File System
Let's model a file system. A File is a leaf, and a Folder is a composite. Both are FileSystemComponents.
Try running this example:
interface FileSystemComponent {
void display(int indent);
}
class File implements FileSystemComponent {
private String name;
public File(String name) { this.name = name; }
@Override
public void display(int indent) {
System.out.println(" ".repeat(indent) + "File: " + name);
}
}
class Folder implements FileSystemComponent {
private String name;
private java.util.List<FileSystemComponent> children = new java.util.ArrayList<>();
public Folder(String name) { this.name = name; }
public void add(FileSystemComponent component) {
children.add(component);
}
@Override
public void display(int indent) {
System.out.println(" ".repeat(indent) + "Folder: " + name);
for (FileSystemComponent child : children) {
child.display(indent + 1);
}
}
}
public class Main {
public static void main(String[] args) {
File file1 = new File("report.pdf");
File file2 = new File("image.jpg");
Folder documents = new Folder("Documents");
documents.add(file1);
documents.add(file2);
Folder root = new Folder("Root");
root.add(documents);
root.add(new File("README.txt"));
root.display(0);
}
}Building & Traversing Trees
In the example, FileSystemComponent is our common interface. Both File (leaf) and Folder (composite) implement it.
Folder can hold other FileSystemComponents, allowing us to build a hierarchical structure. The display method works uniformly whether it's a file or a folder!
Why Use Composite?
The Composite pattern offers several advantages:
- Client Simplicity: Clients don't need to distinguish between individual objects and groups of objects when performing operations.
- Flexibility: It's easy to add new types of components (files or folders) without changing existing client code.
- Tree Structures: Naturally represents hierarchies where objects are composed into larger objects.
Bridge: Decoupling Abstraction
The Bridge pattern helps you "bridge" the gap between an abstraction and its implementation. It decouples them so they can vary independently.
This is useful when you have multiple ways to implement a feature, and you want to avoid a "class explosion" or tight coupling.
Abstraction, Implementor, & More
The Bridge pattern involves these key parts:
- Abstraction: Defines the client-facing interface. It holds a reference to an
Implementorobject. - Refined Abstraction: Extends
Abstraction, providing variations. - Implementor: Defines the interface for implementation classes. It doesn't have to match the
Abstraction's interface exactly. - Concrete Implementor: Implements the
Implementorinterface.
Bridge in Action: Remote Control
Let's make a remote control that works with different devices (TV, Radio). The remote is the abstraction, and the devices are the implementations.
Run this code to see how they connect:
interface Device {
void powerOn();
void powerOff();
void setChannel(int channel);
}
class Tv implements Device {
@Override
public void powerOn() { System.out.println("TV is ON"); }
@Override
public void powerOff() { System.out.println("TV is OFF"); }
@Override
public void setChannel(int channel) { System.out.println("TV Channel: " + channel); }
}
class Radio implements Device {
@Override
public void powerOn() { System.out.println("Radio is ON"); }
@Override
public void powerOff() { System.out.println("Radio is OFF"); }
@Override
public void setChannel(int channel) { System.out.println("Radio Frequency: " + channel + " MHz"); }
}
abstract class RemoteControl {
protected Device device;
public RemoteControl(Device device) { this.device = device; }
public abstract void togglePower();
public abstract void changeChannel(int channel);
}
class BasicRemote extends RemoteControl {
public BasicRemote(Device device) { super(device); }
@Override
public void togglePower() {
if (device instanceof Tv) { // Simple example for illustration
System.out.print("Basic Remote TV: ");
} else if (device instanceof Radio) {
System.out.print("Basic Remote Radio: ");
}
// In a real scenario, device would have a state
// For simplicity, we just toggle based on a dummy state
device.powerOn(); // or powerOff() based on state
}
@Override
public void changeChannel(int channel) {
System.out.print("Basic Remote: ");
device.setChannel(channel);
}
}
public class Main {
public static void main(String[] args) {
Device tv = new Tv();
RemoteControl basicTvRemote = new BasicRemote(tv);
basicTvRemote.togglePower();
basicTvRemote.changeChannel(7);
System.out.println("---");
Device radio = new Radio();
RemoteControl basicRadioRemote = new BasicRemote(radio);
basicRadioRemote.togglePower();
basicRadioRemote.changeChannel(98);
}
}Connecting Abstraction & Impl.
Here, RemoteControl is our abstraction, and Device is the implementor interface. Tv and Radio are concrete implementations.
We can combine any RemoteControl with any Device. This means we can add new remotes (e.g., an AdvancedRemote) or new devices (e.g., a Projector) independently!
Why Use Bridge?
The Bridge pattern brings significant advantages:
- Decoupling: Abstraction and implementation can be extended independently.
- Reduced Complexity: Avoids a combinatorial explosion of classes (e.g.,
BasicTvRemote,AdvancedTvRemote,BasicRadioRemote, etc.). - Increased Flexibility: You can change the implementation at runtime without affecting the client.
Pattern Power-Up
You're designing a graphical user interface where elements can be individual buttons or panels containing other buttons and panels. Which design pattern is best suited to treat both individual buttons and panels uniformly?
Composite & Bridge Summary
Great job! You've explored two powerful structural patterns:
- The Composite pattern simplifies client code by treating individual objects and groups of objects uniformly in a hierarchy.
- The Bridge pattern decouples an abstraction from its implementation, allowing them to evolve independently and reducing complexity.
These patterns are crucial for building flexible and maintainable software systems. Keep practicing!
คำถามที่พบบ่อย
บทเรียน “รูปแบบ Composite และ Bridge” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “รูปแบบ Composite และ Bridge” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clean Architecture & Design Patterns in Practice ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบ Composite และ Bridge”
ทำงานกับ Composite สำหรับโครงสร้างแบบต้นไม้ และ Bridge เพื่อแยกส่วนสิ่งนามธรรมออกจากการใช้งานจริง คุณปฏิบัติ Clean Architecture & Design Patterns in Practice ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clean Architecture & Design Patterns in Practice หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clean Architecture & Design Patterns in Practice บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “รูปแบบ Composite และ Bridge” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clean Architecture & Design Patterns in Practice นี้ได้ไหม
ได้ บทเรียน Clean Architecture & Design Patterns in Practice ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รูปแบบ Adapter และ Decorator
- รูปแบบ Facade และ Proxy
- รูปแบบ Composite และ Bridge
- รูปแบบ Flyweight เพื่อประสิทธิภาพหน่วยความจำ