/**
接口的实际应用:
题目: 两个人A,B开发一个火车票显示功能A负责客户端, B负责服务器端
思路:
1. 抽象出类:
1.1 客户端显示类(Terminal)
1.2 服务器端服务类(TrainService)
1.3 火车票(Ticket)
2. 找出类关系:
2.1 客户端 调用 服务器端 的获取火车票信息显示
TrainService -> Terminal(调用)
2.2 服务器端 提供 火车票信息 给 客户端
Ticket->TrainService(多对1) Ticket -> Terminal(多对多)
3. 找出类属性:
3.1 Ticket(车次,出发地,到达地,票价)
3.2 TrainService(火车站名称)
3.3 Terminal(代售点名称)
4. 找出类方法:
4.1 TrainService: 提供火车票信息 Ticket[] getTickets()
4.2 Terminal: 显示火车票信息 display()
*/
import java.util.Scanner;
public class ApplyInterface
{
public static void main(String[] args)
{
//北京西站火车票服务器打开
TrainService beijingWestService=new BeijingWestTrainService("北京西站");
//北京站火车票服务器打开
TrainService beijingService=new BeijingTrainService("北京站");
//我是北京朝阳区大黄庄的 代售点
Terminal t=new Terminal("北京朝阳区大黄庄的 代售点");
Scanner in =new Scanner(System.in);
System.out.println("请输入要查的火车站代码 1:北京西站 2:北京站");
int trainId=in.nextInt();
if(trainId==1)
{
t.setTrainService(beijingWestService);
}
if(trainId==2)
{
t.setTrainService(beijingService);
}
//打开火车电脑终端 查看火车票信息
t.display();
}
}
class Ticket
{
private String id;//车次
private String startCity;//出发城市
private String endCity;//到达城市
private float price;//票价
public Ticket(String id,String startCity,String endCity,float price)
{
this.id=id;
this.startCity=startCity;
this.endCity=endCity;
this.price=price;
}
public String getId()
{
return this.id;
}
public String getStartCity()
{
return this.startCity;
}
public String getEndCity()
{
return this.endCity;
}
public float getPrice()
{
return this.price;
}
}
interface TrainService
{
/**
A和B约定一个提供火车票的方法
*/
public Ticket[] getTickets();
/**
获取火车站名字
*/
public String getName();
}
class BeijingWestTrainService implements TrainService
{
private String name;
public BeijingWestTrainService(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
/**
提供火车票的实现方法
*/
public Ticket[] getTickets()
{
Ticket[] tickets={
new Ticket("T1","北京","长沙",175f)
};
return tickets;
}
}
class BeijingTrainService implements TrainService
{
private String name;
public BeijingTrainService(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
/**
提供火车票的实现方法
*/
public Ticket[] getTickets()
{
Ticket[] tickets={
new Ticket("T215","北京","吉林",130f)
};
return tickets;
}
}
class Terminal
{
private String proxy;//代售点名称
private Ticket[] tickets;// 火车票引用
private TrainService trainService;// 服务器接口引用
public Terminal(String proxy)
{
this.proxy=proxy;
}
public void setTrainService(TrainService trainService)
{
this.trainService=trainService;
}
/**
显示火车票的信息
思路:
1. 首先要从服务器端 获取 火车票信息
2. 循环把火车票信息显示在电脑终端上
*/
public void display()
{
//获取火车票信息
tickets=trainService.getTickets();
//输出火车票信息
System.out.println(trainService.getName());
System.out.println("车次------出发地------到达地------票价");
if(tickets!=null)
{
for(int i=0;i
{
System.out.println(tickets[i].getId()+"------"+tickets[i].getStartCity()+"------"+tickets[i].getEndCity()+"------"+tickets[i].getPrice());
}
}
}
}