是否在考虑组合的方法中从另一个 class 创建一个对象
Does make an object from another class inside a method considered composition
如果我有这个class
import java.util.Scanner;
public class SimpleCalc {
private int x;
private int y;
private Scanner scan;
public SimpleCalc() {
scan = new Scanner(System.in);
System.out.print("Please Enter The First Number: ");
this.x = scan.nextInt();
System.out.print("Please Enter The Second Number: ");
this.y = scan.nextInt();
}
}
此 class 使用组合概念,因为它具有来自另一个 class "Scanner".
的 "scan" 对象
但是如果我在这样的方法中声明 "scan" 对象会怎样:
public SimpleCalc() {
Scanner scan = new Scanner(System.in);
System.out.print("Please Enter The First Number: ");
this.x = scan.nextInt();
System.out.print("Please Enter The Second Number: ");
this.y = scan.nextInt();
}
那是否考虑了构图概念?
换句话说:组合概念只适用于 classes 还是也适用于方法?
如果您的问题是在设计模式的上下文中并且与复合设计模式特别相关,那么简短的回答是否定的。
正如 GOF 所述:
"Compose objects into tree structure to represent part-whole
hierarchies.Composite lets client treat individual objects and
compositions of objects uniformly".
所以这不适用于方法。
如果我有这个class
import java.util.Scanner;
public class SimpleCalc {
private int x;
private int y;
private Scanner scan;
public SimpleCalc() {
scan = new Scanner(System.in);
System.out.print("Please Enter The First Number: ");
this.x = scan.nextInt();
System.out.print("Please Enter The Second Number: ");
this.y = scan.nextInt();
}
}
此 class 使用组合概念,因为它具有来自另一个 class "Scanner".
的 "scan" 对象但是如果我在这样的方法中声明 "scan" 对象会怎样:
public SimpleCalc() {
Scanner scan = new Scanner(System.in);
System.out.print("Please Enter The First Number: ");
this.x = scan.nextInt();
System.out.print("Please Enter The Second Number: ");
this.y = scan.nextInt();
}
那是否考虑了构图概念?
换句话说:组合概念只适用于 classes 还是也适用于方法?
如果您的问题是在设计模式的上下文中并且与复合设计模式特别相关,那么简短的回答是否定的。
正如 GOF 所述:
"Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly".
所以这不适用于方法。