Skip to the content.

Design Patterns: Structural Patterns

-

What we’ll cover

-

Structural Patterns

-

Facade Pattern

-

Encountering Facade Necessity

-

Defining a facade

public class ListFacade<T> {
    private final List<T> list;
    public ListFacade(List<T> list) { this.list = list; }
    public ListFacade() { this(new ArrayList<>()); }

    public boolean add(T object) { return list.add(object); }
    public void remove(T object) { list.remove(object); }
    public T get(Integer index) { return list.get(index);
    }
    public int size() { return list.size(); }
    public void foreach(Consumer<T> consumer) { list.forEach(consumer); }
}

-

Using a Facade

-

Decorator Pattern

-

Encountering Decorator Necessity

-

Defining Profile

public class Profile {
	// field declaration omitted for brevity
	public Profile(Integer id, String name, Double balance) {
		this.id = id;
		this.name = name;
		this.balance = balance;
	}
	// getter and setter definition omitted for brevity
}

-

Defining Player

public class Player {
	// field declaration omitted for brevity
	public Player(Integer id, String name, Double balance, Profile profile) {
		this.id = id;
		this.name = name;
		this.balance = balance;
		this.profile = profile;
	}
	// getter and setter definition omitted for brevity
}

-

Creating a Decorator

public class Player extends Profile {
	private Profile profile;

	public Player(Profile profile) { this.profile = profile; }

	@Override
	public Integer getId() { return this.profile.getId(); }

	@Override
	public String getName() { return this.profile.getName(); }

	@Override
	public Double getId() { return this.profile.getBalance(); }
}

-

Adapter Pattern

-

Encountering Adapter Necessity

-

Defining an Adapter class

public class TemporalAdapter {
	private Date date;

	public TemporalAdapter(Date date) {
		this.date = date;
	}

	public LocalDate getLocalDate() {
		Instant instant = date.toInstant();
		ZoneId zoneId = ZoneId.of("America/New_York");
		ZonedDateTime zdt = instant.atZone(zoneId);
		LocalDate localDate = zdt.toLocalDate();
		return localDate;
	}
}

-

Using an Adapter class

public void demo() {
	Date date = new Date();
	TemporalAdapter adapter = new TemporalAdapter(date);
	LocalDate localDate = adapter.getLocalDate();
}

-