Java / Java Design Patterns

Using Structural Patterns in Java

This tutorial will guide you through the use of Structural Patterns in Java. It focuses on how these patterns can help organize different classes and objects to form larger struct…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers design patterns to solve common software development problems.

Using Structural Patterns in Java

1. Introduction

This tutorial aims to guide you on how to effectively use Structural Patterns in Java. By the end of this guide, you'll understand how to organize different classes and objects to form larger structures and provide new functionality using these patterns.

1.1 Tutorial Goals

  • Understand the basics of Structural Patterns in Java.
  • Learn how to implement various Structural Patterns.
  • Develop a hands-on understanding through practical examples.

1.2 Prerequisites

  • Basic understanding of Java Programming.
  • Familiarity with Object-Oriented Programming concepts.

2. Step-by-Step Guide

Structural Patterns provide a manner to define relationships between classes or objects so that they can work together to achieve a common goal. They simplify the structure by identifying relationships.

2.1 Adapter Pattern

The Adapter Pattern works as a bridge between two incompatible interfaces. It involves a single class which is responsible to join functionalities of independent or incompatible interfaces.

// Existing way requests are implemented
class OldSystem {
    public void oldRequest() {
        System.out.println("Old System");
    }
}

// New interface
interface NewSystem {
    void newRequest();
}

// Adapter Wrapper class
class Adapter implements NewSystem {
    private OldSystem oldSystem;

    public Adapter(OldSystem oldSystem) {
        this.oldSystem = oldSystem;
    }

    @Override
    public void newRequest() {
        oldSystem.oldRequest();
    }
}

// Using the new system (with adapter)
public class Main {
    public static void main(String[] args) {
        NewSystem newSystem = new Adapter(new OldSystem());
        newSystem.newRequest(); // Outputs: "Old System"
    }
}

2.2 Composite Pattern

The Composite Pattern is used where we need to treat a group of objects in a similar way as a single object. It composes objects in term of a tree structure to represent part as well as whole hierarchies.

import java.util.ArrayList;
import java.util.List;

// Component
interface Employee {
    void showEmployeeDetails();
}

// Leaf
class Developer implements Employee {
    private String name;

    public Developer(String name) {
        this.name = name;
    }

    @Override
    public void showEmployeeDetails() {
        System.out.println("Developer: " + name);
    }
}

// Composite
class Team implements Employee {
    private List<Employee> employeeList = new ArrayList<Employee>();

    @Override
    public void showEmployeeDetails() {
        for(Employee emp:employeeList) {
            emp.showEmployeeDetails();
        }
    }

    public void addEmployee(Employee emp) {
        employeeList.add(emp);
    }
}

// Using composite pattern
public class Main {
    public static void main(String[] args) {
        Employee dev1 = new Developer("John Doe");
        Employee dev2 = new Developer("Jane Doe");

        Team team = new Team();
        team.addEmployee(dev1);
        team.addEmployee(dev2);

        team.showEmployeeDetails();
        // Outputs: "Developer: John Doe", "Developer: Jane Doe"
    }
}

3. Code Examples

We have discussed two Structural Patterns - Adapter and Composite. Now let's dive into more examples.

3.1 Proxy Pattern

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

interface Image {
    void display();
}

class RealImage implements Image {
    private String filename;

    public RealImage(String filename) {
        this.filename = filename;
        loadFromDisk();
    }

    private void loadFromDisk() {
        System.out.println("Loading " + filename);
    }

    @Override
    public void display() {
        System.out.println("Displaying " + filename);
    }
}

class ProxyImage implements Image {
    private RealImage realImage;
    private String filename;

    public ProxyImage(String filename) {
        this.filename = filename;
    }

    @Override
    public void display() {
        if (realImage == null) {
            realImage = new RealImage(filename);
        }
        realImage.display();
    }
}

// Using Proxy Pattern
public class Main {
    public static void main(String[] args) {
        Image image = new ProxyImage("test.jpg");

        // Image will be loaded from disk
        image.display();

        // Image will not be loaded from disk
        image.display();
    }
}

4. Summary

  • We explored Structural Patterns in Java that are helpful in simplifying the structure of classes and objects.
  • We studied Adapter, Composite, and Proxy patterns with examples.

5. Practice Exercises

  1. Implement a Decorator Pattern in Java.
  2. Implement a Bridge Pattern in Java.

Remember, the key to mastering these patterns is through continuous practice. Try to use these patterns in your regular coding tasks where necessary. Take part in coding challenges and try to implement these patterns. Happy coding!

Additional Resources

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help