我知道基本的Java,但我有时会面向对象设计。
我使用的是供应商api,我想将其包装为可重复使用的lib
在其他项目中。
供应商提供的所有服务都是不同的类,没有层次结构等等,但我没有选择更改它。
所以我想使用作文并确保我不会重复自己。
我认为最初要创建一个服务来接收所有服务共有的参数,这个服务将实现api。
我尝试在这里和那里重构这些代码,并且我非常确定我尝试的这个设计在尝试创建单元测试时会注意到一些很大的问题:)
我怎样才能实现更好的设计? 截至目前的代码:
/* This is how I call the service from the vendor today */
class VendorConsumer {
void exampleCake() {
VendorServiceCake vendorServiceCake = new VendorServiceCake();
VendorApiCake cakeApi = a.getCakeApi(1234);
cakeApi.authenticate("user", "password");
cakeApi.cookDeliciousCake(CakeIngredients ingredients);
}
void exampleSellPie() {
VendorServiceSellPie vendorServiceSellPie = new VendorServiceSellPie();
VendorApiSellPie apiSellPie = a.getPieApi(1234); //same parameters as above
apiSellPie.authenticate("user", "password"); //same parameters as above
apiSellPie.sellDeliciousPie(List<Customer> customer);
}
}
// ---------------------------------------------
/* Below is what I'm trying to do */
class UsageTest {
// This is how users of my .jar would call it
void usage() {
BakeryService service = new BakeryServiceCake("user", "password", 1234);
List<Cake> cakeList = service.cookDeliciousCake(CakeIngredients ingrediets);
}
void usage2() {
BakeryService service = new BakeryServiceSellPie("user", "password", 1234);
List<Payments> payments = service.sellDeliciousPie(List<Customer> customer);
}
}
class BakeryService { //is this class useless?
public BakeryService(String user, String pass, int parameterNeeded) {
}
private void checkParameters() {
//do some checkings of the parameters
}
}
class BakeryServiceCake extends BakeryService implements KitchenCakeApi {
KitchenCakeApi api;
public BakeryServiceCake(String user, String pass, int parameterNeeded) {
super(user, pass, parameterNeeded);
this.api = new KitchenCakeApiImpl(user, pass, parameterNeeded)
}
@Override
public void authenticate() {
api.authenticate();
}
@Override
public void cookDeliciousCake(CakeIngredients ingredients) {
api.cookDeliciousCake(ingredients);
}
}
interface KitchenCakeApi {
void authenticate();
void cookDeliciousCake(CakeIngredients ingredients);
}
class KitchenCakeApiImpl implements KitchenCakeApi {
private VendorServiceCake vendorServiceCake;
private VendorApiCake cakeApi;
public KitchenCakeApiImpl(String user, String pass, int parameterNeeded) {
vendorServiceCake = new VendorServiceCake();
cakeApi = a.getCakeApi(parameterNeeded); // that 1234
}
@Override
public void authenticate() {
cakeApi.authenticate("user", "password");
}
@Override
public void cookDeliciousCake(CakeIngredients ingredients) {
cakeApi.cookDeliciousCake(CakeIngredients ingredients);
}
}
谢谢!