理解开闭原则,实现以下样例
public abstract class AbstractButton {
public abstract void view();
}
public class CircleButton extends AbstractButton{
@Override
public void view() {
System.out.println("CircleButton view ...");
}
}
public class RectangleButton extends AbstractButton{
@Override
public void view() {
System.out.println("RectangleButton view ...");
}
}
public class LoginForm {
public void display(AbstractButton button) {
button.view();
}
}
public class LoginTest {
public static void main(String[] args) {
AbstractButton circleButton = new CircleButton();
AbstractButton rectangleButton = new RectangleButton();
LoginForm loginForm = new LoginForm();
loginForm.display(circleButton);
loginForm.display(rectangleButton);
}
}
理解里氏替换原则,实现以下样例
public class Animal {
public double runSpeed;
public double getRunSpeed() {
return runSpeed;
}
public void setRunSpeed(double runSpeed) {
this.runSpeed = runSpeed;
}
}
public class Bird extends Animal{
public double flySpeed;
public double getFlySpeed() {
return flySpeed;
}
public void setFlySpeed(double flySpeed) {
this.flySpeed = flySpeed;
}
public double getFlyTime(double distance) {
return (distance / flySpeed);
}
}
public class BrownKiwi extends Bird {
@Override
public void setRunSpeed(double runSpeed) {
flySpeed = 0;
}
}
public class Swallow extends Bird{
}
public class LSPtest {
public static void main(String[] args) {
Bird bird1 = new Swallow();
Bird bird2 = new BrownKiwi();
bird1.setFlySpeed(120);
bird2.setFlySpeed(150);
System.out.println("如果飞行300公里:");
try {
System.out.println("燕子将飞行" + bird1.getFlyTime(300) + "小时.");
System.out.println("几维鸟将飞行" + bird2.getFlyTime(300) + "小时。");
} catch (Exception err) {
System.out.println("发生错误了!");
}
}
}
理解依赖倒转原则,实现以下样例
public abstract class AbstractSource {
public abstract String source();
}
public abstract class AbstractTransformer {
public abstract String transform();
}
public class DatabaseSource extends AbstractSource{
@Override
public String source() {
return "DatabaseSource";
}
}
public class TextSource extends AbstractSource {
@Override
public String source() {
return "TextSource";
}
}
public class XLSTTransformer extends AbstractTransformer{
@Override
public String transform() {
return "XLSTTransformer";
}
}
public class XMLTransformer extends AbstractTransformer{
@Override
public String transform() {
return "XMLTransformer";
}
}
public class MainClass {
public static void main(String[] args) {
AbstractSource s1 = new DatabaseSource();
AbstractSource s2 = new TextSource();
System.out.println(s1.source());
System.out.println(s2.source());
System.out.println("-----------------------------------------");
AbstractTransformer t1 = new XLSTTransformer();
AbstractTransformer t2 = new XMLTransformer();
System.out.println(t1.transform());
System.out.println(t2.transform());
}
}