Uml图如下:
//实现者(Implementor)
public interface BuildingDesign {
public double computerArea();
}
public class HomeDesign implements BuildingDesign {
double width,length;
int floorNumber;
public HomeDesign(double width,double length,int floorNumber) {
this.width=width;
this.length=length;
this.floorNumber=floorNumber;
}
@Override
public double computerArea() {
return width*length*floorNumber;
}
}
//抽象(Abstraction)
public abstract class ArchitectureCost {
BuildingDesign design;
double unitPrice;
public abstract double giveCost();
}
//细化抽象
public class BuildingCose extends ArchitectureCost {
public BuildingCose(BuildingDesign design,double unitPrice) {
this.design=design;
this.unitPrice=unitPrice;
}
@Override
public double giveCost() {
double area = design.computerArea();
return area*unitPrice;
}
}
模式使用:
public class Appliaction {
public static void main(String[] args) {
double width = 63, height = 30;
int floorNumber = 8;
double unitPrice = 6867.38;
BuildingDesign design = new HomeDesign(width, height, floorNumber);
ArchitectureCost cost = new BuildingCose(design, unitPrice);
double price = cost.giveCost();
System.out.println(price);
}
}