开发者

Usage of Builder Patterns [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Can anyone please tell how the builder and command pattern must be used? And is the following code can be a builder pattern?

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;
    }


The code you have supplied is neither a Command Pattern or Builder pattern. It is a JavaBean which has a constructor with side affects i.e. it calls the DAO. This doesn't seem a good idea.

The Builder pattern is useful when you have many instance variables which need to be set, some of which aren't mandatory. It avoids huge constructors and the need to overload constructors. The Command Pattern isn't a fit at all to what you are doing above - that's to be used when you want some Type to represent an Action or Task in your system.


The builder pattern abstracts the construction of your objects. According to your example I suggest following structure

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);
  }

}

In your application it would be used as follows:

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
         }


    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜