dzh213 / disign-patterns Goto Github PK
View Code? Open in Web Editor NEW大话设计模式读书笔记
大话设计模式读书笔记
定义一个抽象类
public abstract class Operation {
private double numberA;
private double numberB;
public double getNumberA() {
return numberA;
}
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public double getNumberB() {
return numberB;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public abstract double getResult();
}
具体实现:
class OperationAdd extends Operation {
@Override
public double getResult() {
return this.getNumberA()+this.getNumberB();
}
}
class OperationSub extends Operation {
@Override
public double getResult() {
return this.getNumberA() - this.getNumberB();
}
}
class OperationMul extends Operation {
@Override
public double getResult() {
return this.getNumberA() * this.getNumberB();
}
}
class OperationDiv extends Operation {
@Override
public double getResult() {
if (this.getNumberB() == 0) {
throw new RuntimeException("除数不能为0");
}
return this.getNumberA() / this.getNumberB();
}
}
定义工厂类:
public class OperationFactory {
public static Operation createOperation(String operate) {
Operation operation = null;
switch (operate) {
case "+":
operation = new OperationAdd();
break;
case "-" :
operation = new OperationSub();
break;
case "*":
operation = new OperationMul();
break;
case "/":
operation = new OperationDiv();
break;
default:
break;
}
return operation;
}
}
使用:
public class OperationMain {
public static void main(String[] args) {
double numberA = 10;
double numberB = 0;
Operation operation = OperationFactory.createOperation("/");
operation.setNumberA(numberA);
operation.setNumberB(numberB);
System.out.println(operation.getResult());
}
}
策略模式把一个系列的算法封装到一个系列的具体策略类里面,作为一个抽象策略类的子类或策略接口的实现类。简单地说:准备一组算法,并将每一个算法封装起来,使它们可以互换。
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.