Skip to content

Instantly share code, notes, and snippets.

@fgoinai
Created January 5, 2017 16:30
Show Gist options
  • Save fgoinai/88be282c42fd4621c5b281255d8387a4 to your computer and use it in GitHub Desktop.
Save fgoinai/88be282c42fd4621c5b281255d8387a4 to your computer and use it in GitHub Desktop.
interface IBill {
String getType();
void execute(); //假設你要做野
}
class ElectricityBill implements IBill {
int billDay;
int kw;
String region;
Double paidAmount;
public ElectricityBill(String inRegion, int inBillDay, int inKW) {
paidAmount = 0.0;
region = inRegion;
billDay = inBillDay;
kw = inKW;
}
@Override
public String getType() {
return "E";
}
@Override
public void execute() {
//做咩都得
}
}
class GasBill implements IBill {
int billDay;
int kJ;
String rateType;
Double paidAmount;
public GasBill(String inRateType, int inBillDay, int inKJ) {
paidAmount = 0.0;
rateType = inRateType;
billDay = inBillDay;
kJ = inKJ;
}
@Override
public String getType() {
return "G";
}
@Override
public void execute() {
//做你想做既野,好似係
}
}
class Bill {
String type;
IBill bill;
public Bill(String inputType, IBill inBill) {
type = inputType;
bill = inBill;
}
}
class CustomerAccount {
String custName, custAdd, custContact;
private int maxSize = 10;
//如果限定10張單,正路做法係唔好用dynamic allocate size既list/vector, 如果一定要用, 手動check size再做處理
//如果係指一個月會有10種唔同類型既單,係另一個玩法
//1.唔用list/vector,用array
IBill[] custBills1 = new IBill[maxSize];
int index = 0;
//2.用list/vector
List<IBill> custBills2 = new ArrayList<>(maxSize); //或者用LinkedList,睇你需要邊個
Vector<IBill> custBills3 = new Vector<>(maxSize);
public CustomerAccount(String inCustName, String inCustAdd, String inCustContact)
{
custName = inCustName;
custAdd = inCustAdd;
custContact = inCustContact;
}
//1. 用array需要手動指定index
private int getArrayIndex() {
if (index == maxSize) {
index = 0;
return maxSize;
} else {
return index++;
}
}
public void addBill(IBill bill) {
//1. array方法
custBills1[getArrayIndex()] = bill;
//2. list/vector
custBills2.add(bill);
custBills3.add(bill);
//做size control
if (custBills2.size() == maxSize) {
custBills2.remove(0);//清最頭果個,位置可以控制
}
if (custBills3.size() == maxSize) {
custBills3.removeElementAt(0);
}
}
public IBill getBill(int index) {
//1. 如果用array, 需要指定特定index
IBill ret = custBills1[index];
//2. list/vector都係指定index, 但有其他方法拎
ret = custBills2.get(index);
ret = custBills3.elementAt(index);
//2. vector仲可以拎頭尾
ret = custBills3.firstElement();
ret = custBills3.lastElement();
return ret;
}
public void killBill() {
//做個例子,點樣call 唔同class入面同樣名既method (名由interface IBill控制)
//直接call IBill就得,理撚得佢實際咩樣
for (int i = 0; i < custBills1.length; i++) {
custBills1[i].execute();
custBills1[i].getType();
}
for (int i = 0; i < custBills2.size(); i++) {
custBills2.get(i).getType();
//....
}
//仲有iterator玩法
Iterator<IBill> it = custBills2.iterator();
while (it.hasNext()) {
IBill temp = it.next();
temp.getType();
temp.execute();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment