简体   繁体   English

包装类而不重复Java中的所有方法

[英]Wrapping a class without repeating all methods in Java

I want to write a Java class that wraps another class in a specific way for a multi-tenant system: 我想编写一个Java类,以一种特定的方式为多租户系统包装另一个类:

  • All methods of the original class should exist in the new class 原始类的所有方法都应存在于新类中
  • Except that arguments of the new methods should be the same minus 1: the tenant (=current user) 新方法的参数应该相同,但负1:租户(=当前用户)
  • I want to write as little code as possible for the new class. 我想为新类编写尽可能少的代码。 In the best case it should be empty and have all methods "auto-generated" or "auto-detected" at runtime. 在最佳情况下,它应该为空,并且在运行时具有“自动生成”或“自动检测”的所有方法。

Example: 例:

Take this existing class: 参加以下现有课程:

MyService{
   public List<Product> getProducts(Account filterWithUseraccount);
   public List<Purchase> getPurchases(Account filterWithUseraccount, Date fromDate, Date tillDate);
   public List<Category> getCategories(Account filterWithUseraccount, Category parentCategory);
}

And I want to create this new class, but the methods should be "auto-generated": 我想创建这个新类,但是方法应该是“自动生成的”:

MyTenantOrientedService{

   // Assign an account which will be used to call all MyService methods
   private Account filterWithUseraccount;

   // The service being wrapped
   private MyService myService;

   public List<Product> getProducts(){
      return myService.getProducts(filterWithUseraccount);
   }
   public List<Purchase> getPurchases(Date fromDate, Date tillDate){
      return myService.getPurchases(filterWithUseraccount, fromDate, tillDate);
   }
   public List<Category> getCategories(Category parentCategory){
      return myService.getCategories(filterWithUseraccount, parentCategory);
   }
}

As you can see, the methods in MyTenantOrientedService are the same as in MyService, except that the parameter "Account filterWithUseraccount" is never used and can be taken from the private property. 如您所见,MyTenantOrientedService中的方法与MyService中的方法相同,只是参数“ Account filterWithUseraccount”从不使用,并且可以从private属性中获取。

This is a simple example, but imagine a class with a lot of methods, making it a huge chore to create the wrapping functions. 这是一个简单的示例,但请想象一个具有许多方法的类,这使创建包装函数变得非常繁琐。 This is a lot of code duplication and bug can easily be created. 这是很多代码重复,并且可以轻松创建错误。

I believe a solution might exist using AOP or other design pattern, but I can't figure out which. 我相信使用AOP或其他设计模式可能会存在一种解决方案,但我不知道哪种解决方案。

Your IDE handles this kind of tasks for you. 您的IDE会为您处理此类任务。

For example, you could add a member variabile of type MyService inside MyTenantOrientedService and, on Eclipse, right-click on MyTenantOrientedService, then click on "Source -> Generate Delegate Methods" 例如,您可以在MyTenantOrientedService内添加类型为MyService的成员变量,然后在Eclipse上右键单击MyTenantOrientedService,然后单击“源->生成代理方法”

It is applying the Delegation Pattern for you. 它正在为您应用委派模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM