有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

构建器模式的java使用

有谁能告诉我必须如何使用生成器和命令模式吗? 下面的代码是否可以作为生成器模式

public Customer(String name,double age,
     String account)
            throws SQLException {
        this.name = name;
        this.age = age;
        this.account = account;
        Customer.dao.create(this);
    }
public void setAccount(String account) {
        this.account = account;
    }
public void setName(String name) {
        this.name = name;
    }
public void setAge(double age) {
        this.age = age;
    }

共 (2) 个答案

  1. # 1 楼答案

    生成器模式抽象了对象的构造。根据你的例子,我建议如下结构

    public interface Builder {
       public Costumer buildCostumer(String name, double age, String account);
    }
    
    public class ConcreteBuilder implements Builder {
    
      public Costumer buildCostumer(String name, double age, String account) {
         return new Costumer(name, age, account);
      }
    
    }
    

    在您的应用程序中,它将按如下方式使用:

    public class Application {
    
             public static void main(String[] args) {
                  Builder builder = new ConcreteBuilder();
                  Costumer c = builder.buildCostumer("Hugo Bosh", 37, "account");
                  //do what you want with the costumer
             }
    
    
        }
    
  2. # 2 楼答案

    您提供的代码既不是命令模式,也不是生成器模式。它是一个JavaBean,它有一个带有副作用的构造函数,即调用DAO。这似乎不是个好主意

    当您有许多需要设置的实例变量时,生成器模式非常有用,其中一些不是必需的。它避免了庞大的构造函数和重载构造函数的需要。命令模式根本不适合您在上面所做的事情——当您希望某种类型来表示系统中的操作或任务时,可以使用命令模式