簡體   English   中英

位置層次結構數據結構

[英]Location hierarchy data structure

位置層次結構的數據結構或數據模型

I have the following location types,

Airport
City
State
Country

Hierarchy is Country has a state, State has a City and a City has airport.

City:San Francisco To City:Frankfort    Rate is 100$ is stored in the system in some form.

當有人要求從Airport:SFO到Airport:FRA的價格時,應用程序應查找從Airport:SFO到Airport:FRA的任何可用價格。

由於我們沒有人(我們只有城市到城市),因此應用程序應檢查到機場的更高一級,即城市。 因此,應用程序應該能夠找到“機場:SFO”和“機場:法蘭克福”城市,並檢查房價是否可用。 在這種情況下,由於City:San Francisco到City:Frankfort的費率保持為100 $,因此它將收取100 $。

如何在數據結構中表示此位置層次結構(在Java中)? 圖形或樹會有用嗎? 如果可以,請提供一些樣品。

IMO,有兩種自下而上或自上而下的方式(盡管兩者實際上都是基於HAS-A關系的:

自下而上:

1,有班級機場,城市,州,國家

2,機場有城市,城市有州,州有國家變量

現在,無論何時需要費率,都可以轉到機場對象,檢查城市->州->國家等,並相應收費

自頂向下:

1,有國家,州,城市,機場班

2,國家/地區將具有包含州/省的清單,州/省將具有城市的清單,城市將具有機場的清單

我更喜歡第一個,因為維持1的父母價值比維持所有孩子的名單更容易/有效。

您可以嘗試以下樹狀結構

好處

1.跨不同位置類型的統一數據結構。

2.在添加新的位置類型的情況下,無需新的班級。

3.parent查找變得容易。

4.父遞歸遍歷成為可能。

5.遞歸遍歷孩子成為可能。

public class Location
{
    private LocationType locationType;
    private Set<Location> children = new HashSet<Location>();
    private Location parent;

    public int rateTo(Location location)
    {
        int rate = -1;

        Location from = this;
        Location to = location;

        do
        {
            rate = getRate(from, to);
            if (rate > -1)
                break;

            from = from.parent;
            to = to.parent;

            if (from == null || to == null)
                break;
        } while (true);

        return rate;
    }

    public void addChildLocation(Location child)
    {
        child.parent = this;
        children.add(child);
    }

    public int getRate(Location from, Location to)
    {
        //1. implement your own database lookup, etc......
        //2. take care of reverse location parameters also...
        return -1;
    }

    public enum LocationType
    {
        Airport,
        City,
        State,
        Country
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM