首页 > 解决方案 > Create complex class with factory and builder

问题描述

background: I build a class diagram for shopping on the net. For creating a user interface with tow type (golden-User and silver-User) I use the factory pattern.
But the User class become to be very complex.

How can I create this class by bulider and on the other hand the ability to specify the user type such as the factory will remain on the class name (will help me to recognize which type is by polymorphism and not by if&else)

标签: oopdesign-patternsclass-designclass-diagram

解决方案


装饰器模式是一个简单的解决方案:

public class Main {

    public static void main(String[] args) {

        User silverUser = new UserDecorator(new SilverUser("Kyriakos", "Georgiopoulos"));
        User goldenUser = new UserDecorator(new GoldenUser("GoldenUser firstName", "GoldenUser lastName"));
        User nullUser = new UserDecorator(null);

        System.out.println(silverUser.firstName() + " " + silverUser.lastName() + " is " + silverUser.type());
        System.out.println(goldenUser.firstName() + " " + goldenUser.lastName() + " is " + goldenUser.type());
        System.out.println(nullUser.firstName() + " " + nullUser.lastName() + " is " + nullUser.type());
         }
}

interface User {
    String firstName();

    String lastName();

    String type();
}

class SilverUser implements User {

    private final String firstName;
    private final String lastName;

    SilverUser(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() {
        return firstName;
    }

    public String lastName() {
        return lastName;
    }

    public String type() {
        return "SilverUser ";
    }
}

class GoldenUser implements User {

    private final String firstName;
    private final String lastName;

    GoldenUser(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() {
        return firstName;
    }

    public String lastName() {
        return lastName;
    }

    public String type() {
        return "GoldenUser ";
    }
}

class UserDecorator implements User {
    private final User user;
    
    UserDecorator(User user){
        this.user = user;
    }
    
    public String firstName() {
        return user != null && user.firstName() != null && user.firstName().length() > 0 ?
                user.firstName() : "";
    }

    public String lastName() {
        return user != null && user.lastName() != null && user.lastName().length() > 0 ?
                user.lastName() : "";
    }
    
    public String type() {
        return user != null ? user.type() : "NullPointerException";
    }
}


推荐阅读