我需要 2 个对象:最大堆和最小堆。 两个对象都是相同的,但它们的一些方法(例如 swap 或 bubbleUp)以不同的方式比较对象。仅比较行不同:
while (curr > 0 && (heap[parent].compareTo(heap[curr]) < 0)) {
创建具有 boolean 值的 Heap 类来存储最大堆还是最小堆信息是否更好?或者更好地为最小和最大堆创建具有自己的方法的子类?
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
}
}
最佳答案
创建两个具有自己方法的类。如果您正在创建一个类,它可以充当两个不同的类,那么您就违反了著名的《清洁代码》一书的原则之一。
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….
另一个角度是可读性,如果另一个程序员要查看您的代码,那么与两个多态性或两个类解决方案相比,要发现一个类具有两种功能状态要困难得多。
这是我如何使用多态性来解决这个问题。其中共享功能是继承的,自定义功能是在每个类中定义的。
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;
}
}
关于java - 如何告知比较使用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33682732/