Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page

Was this helpful?

  1. Structural Patterns

Private Class Data

  • Control write access to class attributes

  • Separate data from methods that use it

  • Encapsulate class data initialization

  • Providing new type of final - final after constructor

Example - Hide attributes by keeping them elsewhere

In this example, we want to hide user's password variable.

class User {
    private UserData userData;

    public User(String name, String password) {
        userData = new UserData(name, password);
    }

    public String getName() {
        return userData.getName();
    }
}

class UserData {
    private String name;
    private String password;

    public UserData(String name, String password) {
        this.name = name;
        this.password = password;
    }

    public String getName() {
        return name;
    }
}

User of the code does not have to know how is data internally stored in class, he uses the code as normally. But he can't access getPassword() method anywhere.

User john = new User("John", "secret");

This is simplified example, we could be hiding variables, methods or some functionality at initialization of an object.

PreviousDecoratorNextBehavioral Patterns

Last updated 5 years ago

Was this helpful?