所以我有一个抽象的Transaction类,它有多个实现(Payment,File(。
我想要一个事务(抽象(的构建器+实现器。
我做到了:
public abstract class TransactionBuilder
{
protected final Transaction transaction;
public TransactionBuilder(Transaction transaction)
{
this.transaction = transaction;
}
public TransactionBuilder setSignature(byte[] signature)
{
this.transaction.setSignature(signature);
return this;
}
public TransactionBuilder setPreviousHash(String previousHash)
{
this.transaction.setPreviousHash(previousHash);
return this;
}
public abstract Transaction build();
}
PaymentBuilder类的示例:
public class PaymentBuilder extends TransactionBuilder
{
public PaymentBuilder(String from, String to, double amount)
{
super(new Payment(from, to, amount));
}
public PaymentBuilder addAmount(double amount)
{
((Payment) this.transaction).amount += amount;
}
@Override
public Payment build()
{
return (Payment) this.transaction;
}
}
每个字段都有一个getter/setter,Transaction:
public abstract class Transaction
{
//Used for serialization
private String type;
private String previousTransactionHash;
private String hash;
private String signature;
private String fromAddress;
private String toAddress;
private Instant timeStamp;
public Transaction(String type, String from, String to)
{
this.type = type;
this.fromAddress = from;
this.toAddress = to;
this.timeStamp = Instant.now();
setHash();
}
如何使用:
Payment payment = new PaymentBuilder(from, to, amount)
.setPreviousHash(previousHash)
.build();
但是当我调用setSignature((时;类型不匹配:无法从交易转换为支付"所以我需要将其转换为付款,我如何避免这种情况?我可以吗?
您可以使抽象生成器具有泛型,泛型类型是它生成的事务类型。
public abstract class TransactionBuilder<T extends Transaction> {
...
public abstract T build();
}
public class PaymentBuilder extends TransactionBuilder<Payment> {
@Override
public Payment build() {
...
}
}
感谢@khelwood,我最终使我的抽象生成器通用化:
TransactionBuilder:
public abstract class TransactionBuilder<T extends Transaction>
{
protected final T transaction;
public TransactionBuilder(T transaction)
{
this.transaction = transaction;
}
public TransactionBuilder<T> setSignature(byte[] signature)
{
this.transaction.setSignature(signature);
return this;
}
public TransactionBuilder<T> setPreviousHash(String previousHash)
{
this.transaction.setPreviousHash(previousHash);
return this;
}
public abstract T build();
}
PaymentBuilder:
public class PaymentBuilder extends TransactionBuilder<Payment>
{
public PaymentBuilder(String from, String to, double amount)
{
super(new Payment(from, to, amount));
}
public PaymentBuilder addAmount(double amount)
{
this.transaction.amount += amount;
}
@Override
public Payment build()
{
return this.transaction;
}
}