Joh*_*ohn 13 java design-patterns adapter
问题描述: 我希望能够将方法列表传递给其他类,其中只在一个类中定义了方法.如果方法(其中一些具有输入参数和非void返回类型)在一个类中定义,我希望能够将其中一些的列表(可能有重复项)作为参数传递给其他类的构造函数.
代码描述: 下面的代码是一个粗略的例子,如果它有损于主要目标,可以忽略.另一个例子,除了下面的例子之外,将是一个方法,其中方法是int Add(int n1,int n2),int Subtract(int n1,int n2),Multiply等.并且接口有一个方法叫做int MathOperation(int n1,int n2).
尝试解决问题: 适配器模式似乎具有我正在寻找的功能,但我只看到了接口中的方法没有输入或输出参数的示例.我为此问题编写的示例实现在下面发布.
问题类比: 您有一个随机图片生成器Web服务.有30种突变可以应用于图像.客户端连接并单击"生成"按钮,其中一些函数的随机列表将传递给Web服务中的某个其他类,然后继续使用它自己的数据运行这些函数,同时还收集并可能重新使用返回生成一些变异的猫图像的值.它不能只显式调用其他类中的方法,因为该进程需要在运行时随机完成.这就是为什么我倾向于生成随机的方法列表的想法,这些方法在单击"生成"按钮时按顺序执行.
我希望我已经清楚了.
public class SomeClass {
...
public double UseWrench(double torque, boolean clockwise) { ... }
public double UsePliers(double torque, boolean clockwise) { ... }
public double UseScrewDriver(double torque, boolean clockwise) { ... }
public boolean UseWireCutters(double torque) { ... }
interface IToolActions {
double TurnFastener(double torque, boolean clockwise);
boolean CutWire(double torque);
}
private IToolActions[] toolActions = new IToolActions[] {
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseWrench(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UsePliers(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseScrewDriver(double torque, boolean clockwise); } },
new IToolActions() { public boolean CutWire(double torque) { boolean UseWireCutters(double torque); } },
};
}
public class Worker<T> {
public List<? extends IToolActions> toolActions;
public Worker(List<? extends IToolActions> initialToolSet){
toolActions = initialToolActions;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然@alainlompo有一般的想法,但Java 8通过使用诸如BiConsumer(对于双精度)甚至只是Consumer对类对象的东西来大大简化了这一点.事实上,你可以真的疯了,并有一个方法接受varargs lambdas:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
}
public class Worker {
@SafeVarargs
public Worker(SomeClass example, Consumer<? extends SomeClass>... operations) {
for (Consumer bc : operations) {
bc.accept(example);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,这很容易简化:
SomeClass c = new SomeClass();
new Worker(c, SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
Run Code Online (Sandbox Code Playgroud)
虽然它似乎有点尴尬地应用它(由于它是一个适配器模式),你可以很容易地看到它如何适用于类体:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
@SafeVarargs
public void operate(Consumer<? extends SomeClass>... operations) {
for (Consumer<? extends SomeClass> bc : operations) {
bc.accept(example);
}
}
}
//Elsewheres
SomeClass c = new SomeClass();
c.operate(SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
Run Code Online (Sandbox Code Playgroud)
当然,你不需要varargs,它也可以简单地传递一个 Collection
但等等还有更多!!!
如果你想要一个结果,你甚至可以通过一个自我回归的方法Function,例如:
public class SomeClass {
public double chanceOfSuccess(Function<? super SomeClass, ? extends Double> modifier) {
double back = /* some pre-determined result */;
return modifier.apply(back); //apply our external modifier
}
}
//With our old 'c'
double odds = c.chanceOfSuccess(d -> d * 2); //twice as likely!
Run Code Online (Sandbox Code Playgroud)
Java 8中的Function API提供了更多的灵活性,使得像这样的复杂问题难以简化.
@John 这是我如何解决你的问题的。
我使用了 MathOperations 的案例来使其更简单。我认为首先我最好在 SomeClass 之外拥有接口,例如:
public interface MathOperable {
public int mathOperation(int n1, int n2);
}
Run Code Online (Sandbox Code Playgroud)
我创建了两个实现此接口的类示例,并在 SomeClass 中创建了一个匿名实现(我做了一个加法、乘法和一个匿名“减法”)
public class Add implements MathOperable {
public int mathOperation(int n1, int n2) {
return n1 + n2;
}
public String toString() {
return "<addition>";
}
}
Run Code Online (Sandbox Code Playgroud)
重写 toString() 只是为了让我将在帖子末尾展示的示例更具可读性。
public class Multiply implements MathOperable {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1 * n2;
}
public String toString() {
return "<multiplication>";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 SomeClass 类,它包含一个 getRandomListOfOperations,我在其中模拟单击按钮完成时发生的情况
public class SomeClass {
private static MathOperable addition = new Add();
private static MathOperable multiplication = new Multiply();
// Anonymous substraction
private static MathOperable substraction = new MathOperable() {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1-n2;
}
public String toString() {
return "<substraction>";
}
};
public List<MathOperable> getRandomListOfOperations() {
// We put the methods in an array so that we can pick them up later randomly
MathOperable[] methods = new MathOperable[] {addition, multiplication, substraction};
Random r = new Random();
// Since duplication is possible whe randomly generate the number of methods to send
// among three so if numberOfMethods > 3 we are sure there will be duplicates
int numberOfMethods = r.nextInt(10);
List<MathOperable> methodsList = new ArrayList<MathOperable>();
// We pick randomly the methods with duplicates
for (int i = 0; i < numberOfMethods; i++) {
methodsList.add(methods[r.nextInt(3)]);
}
return methodsList;
}
public void contactSomeOtherClass() {
new SomeOtherClass(getRandomListOfOperations());
}
}
Run Code Online (Sandbox Code Playgroud)
现在这是我的 SomeOtherClass (可能对应于您的 Worker 类)
public class SomeOtherClass<T extends MathOperable> {
Random r = new Random();
List<T> operations;
public SomeOtherClass(List<T> operations) {
this.operations = operations;
runIt();
}
public void runIt() {
if (null == operations) {
return;
}
// Let's imagine for example that the new result is taken as operand1 for the next operation
int result = 0;
// Here are examples of the web service own datas
int n10 = r.nextInt(100);
int n20 = r.nextInt(100);
for (int i = 0; i < operations.size(); i++) {
if (i == 0) {
result = operations.get(i).mathOperation(n10, n20);
System.out.println("Result for operation N " + i + " = " + result);
} else {
// Now let's imagine another data from the web service operated with the previous result
int n2 = r.nextInt(100);
result = operations.get(i).mathOperation(result, n2);
System.out.println("Current result for operation N " + i + " which is " + operations.get(i) +" = " + result);
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
我有一个简单的测试类,其中包含连接两个类的 main
public class SomeTestClass {
public static void main(String[] args) {
SomeClass classe = new SomeClass();
classe.contactSomeOtherClass();
}
}
Run Code Online (Sandbox Code Playgroud)
现在举几个执行的例子:

还有另一个例子!

我希望这会有所帮助!