/*
* 面相抽象编程
*使用对台进行编程的核心技术之是使用上转型对象,即将abstract 类生命对象作为一个子类的上转对象,那么这个上转对象就可以调用子类重的方法,
*所谓面向抽象编程,是指设计一个类时,不让该类面向具体的类,而是面向一个抽象的类,即所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象。
*/
//通过面向抽象来设计Pillar类,使得该类不依赖具体类,因此每当系统增加新的Geometry的子类的时候,如增加一个Triangle子类,就不用再修改Pillar类的任何代码,就可以使用Pillar创建出具有三角形低的柱体
public abstract class Geometry
{
public abstract double getArea();
}
public class Pillar{//设计一个类使其面向一个抽象的类,而不是具体的类,
Geometry bottom;//抽象类Geometry声明的对象(类中的数据是抽象类生命的对象)
double height;
Pillar (Geometry bottom,double height){
this.bottom=bottom;
this.height=height;
}
public double getVolume(){
return bottom.getArea()*height;//bottom可以调用子类重写的getArea()方法。
}
}
//下列Circle和Rectangle 类都是Gmometry的子类,二者都必须重写getArea()方法,来计算各自的面积
//Circle.java
public class Circle extends Geometry{
double r;
Circle(int r){
this.r=r;
}
public double getArea(){
return 3.14*r*r;
}
}
//Rectangle.java
public class Rectangle extends Geometey{
double a,b;
Rectangle(double a,double b){
this.a=a;
this.b=b;
}
public class getArea(){
return a*b;
}
}
//APPlication.java
public class Application{
public static void main(String[] args){
Pillar pillar;
Geometry bottom;
bottom=new Rectangle(12,22);//上转型对象
pillar=new Pillar(bottom,58);//pillar是具有矩形底的柱体
System.out.println("矩形体的主体体积"+pillar.getVolume());
bottom=new Circle(10);
pillar=new Pillar(bottom,58);
System.out.println("圆形体的主体体积:"+pillar.getVolume());
}
}
/*开-闭原则
* 就是让设计的系统对扩展开放,对修改关闭
* 本质就是当系统中增加模块的时候,不需要修改现有的模块。
* 再设计系统时,首先考虑到用户需求的变化,将对用户变化的部分设计为对扩展开放,而设计的核心部分是指经过精心考虑之后确定的基本结构,这部分对修改是关闭的,既不能因为用户需求的变化而发生改变,因为这部分不是用来应对需求变化的。
* 如果系统遵守了开-闭原则,那么系统一定是利于维护的。
*/
//设计一格 动物模拟器,希望设计的模拟器可以模拟很多动物的声音
//Animal.java
public abstract class Animal{
public abstract void cry();
public abstract String getAnimalNmae();
}
//Simulator.java
public class Simulator{
public void palySound(Animal animal){
System.out.println("现在播放"+animal.getAnimalNmae()+"类的声音: ");
animal.cry();
}
}
//dog.java
public class Dog extends Animal{
public void cry(){
System.out.println("wang...wang");
}
public String getAnimalName(){
return "dog";
}
}
//cat.java
public class Cat extends Animal{
public void cry(){
System.out.println("meo..meo");
}
public String getAnimalName(){
return "cat";
}
}
public class Application{
public static void main(String[] args){
Simulator simulator=new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}
面向抽象编程
最新推荐文章于 2021-08-09 23:50:52 发布