如何告知比较使用的方法
How to inform method which comparision use
我需要 2 个对象:最大堆和最小堆。
这两个对象将是相同的,但它们的某些方法(如 swap 或 bubbleUp)以不同的方式比较对象。只有比较行不同:
while (curr > 0 && (heap[parent].compareTo(heap[curr]) < 0)) {
创建具有存储信息的布尔值的堆 class 是最大还是最小堆更好?或者最好为最小和最大堆创建子classes,它们将有自己的方法?
public abstract class Heap {
private int[] values = new int[];
public void SomeHeapMethod()
{
if(values[0].compareTo(values[1]) > 0 ) //this would be diffent for max and min heap
}
}
如果能把比较函数作为参数的话会更简单。作为参考,您可以查看 Help with understanding a function object or functor in Java,其中讨论了如何处理上述功能。
用各自的方法创建两个 class。如果您正在创建一个 class,它可以充当两个不同的 classes,那么您违反了著名的 Clean Code 一书中的原则之一。
In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility….
另一个角度是可读性,如果另一个程序员要查看您的代码,则很难发现 class 具有两种功能状态,而两个多态性或两个 classes 解决方案。
下面是我将如何使用多态性来解决这个问题。其中共享功能被继承,自定义功能在每个 class.
中定义
public abstract class Heap {
private Integer[] values;
public int compare(int i , int j)
{
throw new RuntimeException("Not implemented");
}
public void SomeHeapMethod()
{
if(this.compare(values[0], values[1]) > 0)
return;
}
}
class MinHeap extends Heap
{
public int compare(int i , int j)
{
return i + j % 2;
}
}
class MaxHeap extends Heap
{
public int compare(int i , int j)
{
return i + j % 1;
}
}
我需要 2 个对象:最大堆和最小堆。 这两个对象将是相同的,但它们的某些方法(如 swap 或 bubbleUp)以不同的方式比较对象。只有比较行不同:
while (curr > 0 && (heap[parent].compareTo(heap[curr]) < 0)) {
创建具有存储信息的布尔值的堆 class 是最大还是最小堆更好?或者最好为最小和最大堆创建子classes,它们将有自己的方法?
public abstract class Heap {
private int[] values = new int[];
public void SomeHeapMethod()
{
if(values[0].compareTo(values[1]) > 0 ) //this would be diffent for max and min heap
}
}
如果能把比较函数作为参数的话会更简单。作为参考,您可以查看 Help with understanding a function object or functor in Java,其中讨论了如何处理上述功能。
用各自的方法创建两个 class。如果您正在创建一个 class,它可以充当两个不同的 classes,那么您违反了著名的 Clean Code 一书中的原则之一。
In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility….
另一个角度是可读性,如果另一个程序员要查看您的代码,则很难发现 class 具有两种功能状态,而两个多态性或两个 classes 解决方案。
下面是我将如何使用多态性来解决这个问题。其中共享功能被继承,自定义功能在每个 class.
中定义public abstract class Heap {
private Integer[] values;
public int compare(int i , int j)
{
throw new RuntimeException("Not implemented");
}
public void SomeHeapMethod()
{
if(this.compare(values[0], values[1]) > 0)
return;
}
}
class MinHeap extends Heap
{
public int compare(int i , int j)
{
return i + j % 2;
}
}
class MaxHeap extends Heap
{
public int compare(int i , int j)
{
return i + j % 1;
}
}