0
私は、クラス(エンティティ)と訪問者のデザインパターンを抽象クラスとして、マネージャメソッド(コードの最後のスニペット)でケーシングを使用しないでください。以下は、BaseEntityと呼ばれるエンティティの抽象クラスです。これは実際の例ではなく、疑似コードです。訪問者の抽象クラス - typeOfに似ています
public abstract class BaseEntity {
@Reference
protected List<String> items = new ArrayList<>();
public BaseEntity() {
}
public List<String> getItems() {
return items;
}
public void setItems(List<String> items) {
this.items = items;
}
}
下に、抽象クラスから3つの派生クラスがあります。
@Entity("CollectionA")
public class EntityA extends BaseEntity {
//code
}
@Entity("CollectionB")
public class EntityB extends BaseEntity {
//code
}
@Entity("CollectionC")
public class EntityC extends BaseEntity {
//code
}
次に、訪問者を作成してマネージャーで再利用し、instanceOfを使用しないようにしました。
public interface UpdateEntityVisitor {
void create(EntityA entityA);
void create(EntityB entityB);
void create(EntityC entityC);
}
public class UpdateEntityVisitorImpl implements UpdateEntityVisitor {
private final Factory factory;
public UpdateEntityVisitorImpl() {
factory = new FactoryImpl();
}
public UpdateEntityVisitorImpl(Factory factory) {
this.factory = factory;
}
@Override
public void create(EntityA entityA) {
factory.getEntityA().create(entityA);
}
@Override
public void create(EntityB entityB) {
factory.getEntityB().create(entityB);
}
@Override
public void create(EntityC entityC) {
factory.getEntityC().create(entityC);
}
}
最後に、私はBaseEntityから適切なクラスへのキャストを避けるため、以下のメソッドを持つマネージャクラスです。マネージャで上記の訪問者クラスを再利用する方法がありますか?
public void updateEntity(BaseEntity entity) {
if (checkSmth()) {
updateCollectionA((EntityA) entity);
} else {
updateCollectionB((EntityB) entity);
}
}
私はtypeof演算https://github.com/nurkiewicz/typeofと呼ばれるこの非常に便利なライブラリが見つかりましたが、私の現在のチームにそれをより明確にする他の方法がある場合、私は思っていました。
ありがとうございます。私はもちろんそれを試みました。事実、updateCollectionAとupdateCollectionBはEntityAとEntityBのような適切なクラスを使い、それぞれのメソッドは適切なDAOを使って操作を実行します。残念ながらジェネリックは許可されていません。 PS。私たちはSpringを使用していませんが、これは主な障害のようです: –