public class Singleton{
private static final Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return singleton;
}
}
1.4、懒汉式创建单例对象
我们再来回顾懒汉式的核心方法
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle:绘制长方形");
}
}
Square
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square:绘制正方形");
}
}
Circle
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle:绘制圆形");
}
}
工厂类
ShapeFactory
public class ShapeFactory {
public static Shape createShape(String shapeType) {
if ("Rectangle".equalsIgnoreCase(shapeType)) {
return new Rectangle();
}
if ("Square".equalsIgnoreCase(shapeType)) {
return new Square();
}
if ("Circle".equalsIgnoreCase(shapeType)) {
return new Circle();
}
return null;
}
}
工厂类测试
ShapeFactoryTest
public class ShapeFactoryTest {
public static void main(String[] args) {
Shape rectangle = ShapeFactory.createShape("Rectangle");
rectangle.draw();
Shape square = ShapeFactory.createShape("Square");
square.draw();
Shape crcle = ShapeFactory.createShape("Circle");
crcle.draw();
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle:绘制长方形");
}
}
Square
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square:绘制正方形");
}
}
Circle
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle:绘制圆形");
}
}
图形工厂类编写
ShapeFactory
public class ShapeFactory extends AbstractFactory {
@Override
public Shape createShape(String shapeType) {
if ("Rectangle".equalsIgnoreCase(shapeType)) {
return new Rectangle();
}
if ("Square".equalsIgnoreCase(shapeType)) {
return new Square();
}
if ("Circle".equalsIgnoreCase(shapeType)) {
return new Circle();
}
return null;
}
@Override
public Color createColor(String color) {
return null;
}
}
颜色产品接口类
Color
public interface Color {
void fill();
}
颜色产品实现类
Red
public class Red implements Color {
@Override
public void fill() {
System.out.println("Red:填充红色");
}
}
Green
public class Green implements Color {
@Override
public void fill() {
System.out.println("Green:填充绿色");
}
}
Blue
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Blue:填充蓝色");
}
}
颜色工厂类编写
ColorFactory
public class ColorFactory extends AbstractFactory {
@Override
public Shape createShape(String shapeType) {
return null;
}
@Override
public Color createColor(String colorType) {
if ("Red".equalsIgnoreCase(colorType)) {
return new Red();
}
if ("Green".equalsIgnoreCase(colorType)) {
return new Green();
}
if ("Blue".equalsIgnoreCase(colorType)) {
return new Blue();
}
return null;
}
}
产品家族抽象类
AbstractFactory
public abstract class AbstractFactory {
public abstract Shape createShape(String shapeType);
public abstract Color createColor(String colorType);
}
抽象类的工厂类
AbstractFactoryProducer
public class AbstractFactoryProducer {
public static AbstractFactory createFactory(String choice) {
if ("Shape".equalsIgnoreCase(choice)) {
return new ShapeFactory();
}
if ("Color".equalsIgnoreCase(choice)) {
return new ColorFactory();
}
return null;
}
}
抽象工厂类测试
AbstractFactoryProducerTest
public class AbstractFactoryProducerTest {
public static void main(String[] args) {
AbstractFactory shapeFactory = AbstractFactoryProducer.createFactory("Shape");
Shape rectangle = shapeFactory.createShape("Rectangle");
rectangle.draw();
Shape square = shapeFactory.createShape("Square");
square.draw();
Shape circle = shapeFactory.createShape("Circle");
circle.draw();
AbstractFactory colorFactory = AbstractFactoryProducer.createFactory("Color");
Color red = colorFactory.createColor("Red");
red.fill();
Color green = colorFactory.createColor("Green");
green.fill();
Color blue = colorFactory.createColor("Blue");
blue.fill();
}
}
//身份证对象
class IdCard {
private String id;
public IdCard(String id) {
this.id = id;
}
@Override
public String toString() {
return id;
}
}
Person
//代表人对象
public class Person implements Cloneable {
private String name;
private int age;
private IdCard idCard;
public Person(String name, int age, IdCard idCard) {
this.name = name;
this.age = age;
this.idCard = idCard;
}
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
@Override
public String toString() {
return "Person{" +
"personHashCode=" + this.hashCode() +
", name='" + name + '\'' +
", age=" + age +
", idCard=" + idCard +
", idCardHashCode=" + idCard.hashCode() +
'}';
}
//浅克隆已经帮我们实现了
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
PersonTest
public class PersonTest {
public static void main(String[] args) throws CloneNotSupportedException {
//创建一个对象
Person person = new Person("张三", 20, new IdCard("10086"));
//克隆两个对象
Person person1 = (Person) person.clone();
Person person2 = (Person) person.clone();
//打印三人信息
System.out.println(person);
System.out.println(person1);
System.out.println(person2);
}
}
//代表人对象
public class Person implements Cloneable {
private String name;
private int age;
private IdCard idCard;
public Person(String name, int age, IdCard idCard) {
this.name = name;
this.age = age;
this.idCard = idCard;
}
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
@Override
public String toString() {
return "Person{" +
"personHashCode=" + this.hashCode() +
", name='" + name + '\'' +
", age=" + age +
", idCard=" + idCard +
", idCardHashCode=" + idCard.hashCode() +
'}';
}
//深克隆我们需要自己手动实现,在引用对象中也需要实现clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
//完成对当前基本数据类型
//注:String类型通过常量赋值时相当于基本数据类型,通过new关键字创建对象时便是引用数据类型
Object person = super.clone();
//对引用类型进行单独处理
Person p = (Person) person;
IdCard idCard = (IdCard) p.getIdCard().clone();//实现自己的克隆
p.setIdCard(idCard);
return p;
}
}
PersonTest
public class PersonTest {
public static void main(String[] args) throws CloneNotSupportedException {
//创建一个对象
Person person = new Person("张三", 20, new IdCard("10086"));
//克隆两个对象
Person person1 = (Person) person.clone();
Person person2 = (Person) person.clone();
//打印三人信息
System.out.println(person);
System.out.println(person1);
System.out.println(person2);
}
}
//身份证对象
class IdCard implements Serializable {
private String id;
public IdCard(String id) {
this.id = id;
}
@Override
public String toString() {
return id;
}
}
Person
//代表人对象
public class Person implements Serializable {
private String name;
private int age;
private IdCard idCard;
public Person(String name, int age, IdCard idCard) {
this.name = name;
this.age = age;
this.idCard = idCard;
}
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
@Override
public String toString() {
return "Person{" +
"personHashCode=" + this.hashCode() +
", name='" + name + '\'' +
", age=" + age +
", idCard=" + idCard +
", idCardHashCode=" + idCard.hashCode() +
'}';
}
//手动实现深克隆方法
public Person deepClone() {
//创建流对象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
//序列化
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
return (Person) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
//关闭流
try {
ois.close();
bis.close();
oos.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
PersonTest
public class PersonTest {
public static void main(String[] args) {
//创建一个对象
Person person = new Person("张三", 20, new IdCard("10086"));
//克隆两个对象
Person person1 = person.deepClone();
Person person2 = person.deepClone();
//打印三人信息
System.out.println(person);
System.out.println(person1);
System.out.println(person2);
}
}
public class House {
private String ground;
private String wall;
private String roofed;
public String getGround() {
return ground;
}
public void setGround(String ground) {
this.ground = ground;
}
public String getWall() {
return wall;
}
public void setWall(String wall) {
this.wall = wall;
}
public String getRoofed() {
return roofed;
}
public void setRoofed(String roofed) {
this.roofed = roofed;
}
@Override
public String toString() {
return "House{" +
"ground='" + ground + '\'' +
", wall='" + wall + '\'' +
", roofed='" + roofed + '\'' +
'}';
}
}
抽象建造者
HouseBuilder
public abstract class HouseBuilder {
//创建产品对象
protected House house = new House();
//生产产品流程
public abstract void buildGround(); //1.打地基
public abstract void buildWall(); //2.砌墙面
public abstract void buildRoofed(); //3.盖楼顶
//返回产品对象
public House getResult() {
return house;
}
}
工程指挥者
HouseDirector
public class HouseDirector {
private HouseBuilder houseBuilder;
public HouseDirector(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
public House build(){
houseBuilder.buildGround();
houseBuilder.buildWall();
houseBuilder.buildRoofed();
return houseBuilder.getResult();
}
}
具体建造者:别墅
VillaHouse
public class VillaHouse extends HouseBuilder {
@Override
public void buildGround() {
house.setGround("100平");
System.out.println("别墅:打地基");
}
@Override
public void buildWall() {
house.setWall("每面墙高三米");
System.out.println("别墅:砌墙面");
}
@Override
public void buildRoofed() {
house.setRoofed("欧式风格屋顶");
System.out.println("别墅:盖楼顶");
}
}
具体建造者:高楼
HighHouse
public class HighHouse extends HouseBuilder{
@Override
public void buildGround() {
house.setGround("200平");
System.out.println("高楼:打地基");
}
@Override
public void buildWall() {
house.setWall("每面墙高四米");
System.out.println("高楼:砌墙面");
}
@Override
public void buildRoofed() {
house.setRoofed("中国复古屋顶");
System.out.println("高楼:盖楼顶");
}
}
产品使用端
Client
public class Client {
public static void main(String[] args) {
House house1 = new HouseDirector(new VillaHouse()).build();
System.out.println(house1);
System.out.println("====================");
House house2 = new HouseDirector(new HighHouse()).build();
System.out.println(house2);
}
}
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
if (this.handlerAdapters != null) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(handler)) {
return adapter;
}
}
}
throw new ServletException("No adapter for handler [" + handler + "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}
public interface Component {
public void add(Component c);
public void remove(Component c);
public Component getChild(int i);
public void operation();
}
树叶构件
Leaf
public class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
public void add(Component c) {
}
public void remove(Component c) {
}
public Component getChild(int i) {
return null;
}
public void operation() {
System.out.println("树叶" + name + ":被访问!");
}
}
树枝构件
Composite
public class Composite implements Component {
private ArrayList children = new ArrayList<>();
public void add(Component c) {
children.add(c);
}
public void remove(Component c) {
children.remove(c);
}
public Component getChild(int i) {
return children.get(i);
}
public void operation() {
for (Object obj : children) {
((Component) obj).operation();
}
}
}
客户端测试
CompositePattern
public class CompositePattern {
public static void main(String[] args) {
Component c0 = new Composite();
Component c1 = new Composite();
Component leaf1 = new Leaf("1");
Component leaf2 = new Leaf("2");
Component leaf3 = new Leaf("3");
c0.add(leaf1);
c0.add(c1);
c1.add(leaf2);
c1.add(leaf3);
c0.operation();
}
}
public interface Component {
public void operation();
}
树叶构件
Leaf
public class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
public void operation() {
System.out.println("树叶" + name + ":被访问!");
}
}
树枝构件
Composite
public class Composite implements Component {
private ArrayList children = new ArrayList<>();
public void add(Component c) {
children.add(c);
}
public void remove(Component c) {
children.remove(c);
}
public Component getChild(int i) {
return children.get(i);
}
public void operation() {
for (Object obj : children) {
((Component) obj).operation();
}
}
}
客户端测试
CompositePattern
public class CompositePattern {
public static void main(String[] args) {
Composite c0 = new Composite();
Composite c1 = new Composite();
Component leaf1 = new Leaf("1");
Component leaf2 = new Leaf("2");
Component leaf3 = new Leaf("3");
c0.add(leaf1);
c0.add(c1);
c1.add(leaf2);
c1.add(leaf3);
c0.operation();
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
Rectangle
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
Square
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
外观角色类
ShapeMaker
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle() {
circle.draw();
}
public void drawRectangle() {
rectangle.draw();
}
public void drawSquare() {
square.draw();
}
}
最终测试类
FacadePatternDemo
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}
结果:
Circle::draw()
Rectangle::draw()
Square::draw()
5.4、应用
在Mybatis源码org.apache.ibatis.session.Configuration类中以 new 开头的方法,下图以newExecutor方法为例:
public class Point {
private int x; //外部状态:代表棋子横坐标
private int y; //外部状态:代表棋子纵坐标
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
抽象享元对象
ChessPieces
public interface ChessPieces {
void downPieces(Point p); //落子方法
}
具体享元对象
WhiteChessPieces
public class WhiteChessPieces implements ChessPieces {
private String color; //内部状态:代表棋子颜色
public WhiteChessPieces() {
this.color = "白";
}
@Override
public void downPieces(Point p) {
System.out.println(color + "子落入横坐标" + p.getX() + ",纵坐标" + p.getY());
}
}
BlackChessPieces
public class BlackChessPieces implements ChessPieces {
private String color; //内部状态:代表棋子颜色
public BlackChessPieces() {
this.color = "黑";
}
@Override
public void downPieces(Point p) {
System.out.println(color + "子落入横坐标" + p.getX() + ",纵坐标" + p.getY());
}
}
享原工厂对象
ChessPiecesFactory
public class ChessPiecesFactory {
private HashMap pools = new HashMap<>();
public ChessPieces getChessPieces(String color) {
if (!pools.containsKey(color)) {
if ("白".equals(color)) {
pools.put(color, new WhiteChessPieces());
}
if ("黑".equals(color)) {
pools.put(color, new BlackChessPieces());
}
}
return pools.get(color);
}
}
最终测试类
Client
public class Client {
public static void main(String[] args) {
ChessPiecesFactory chessPiecesFactory = new ChessPiecesFactory();
ChessPieces cp1 = chessPiecesFactory.getChessPieces("白");
ChessPieces cp2 = chessPiecesFactory.getChessPieces("白");
ChessPieces cp3 = chessPiecesFactory.getChessPieces("黑");
ChessPieces cp4 = chessPiecesFactory.getChessPieces("黑");
Point p1 = new Point(1, 1);
Point p2 = new Point(2, 2);
Point p3 = new Point(3, 3);
Point p4 = new Point(4, 4);
cp1.downPieces(p1);
cp2.downPieces(p2);
cp3.downPieces(p3);
cp4.downPieces(p4);
System.out.println("====================");
System.out.println(cp1 == cp2);
System.out.println(cp3 == cp4);
}
}
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//模板
public final void play() {
//初始化游戏
initialize();
//开始游戏
startPlay();
//结束游戏
endPlay();
}
}
具体子类
Football
public class Football extends Game {
@Override
void initialize() {
System.out.println("Football Game Initialized.");
}
@Override
void startPlay() {
System.out.println("Football Game Started.");
}
@Override
void endPlay() {
System.out.println("Football Game Finished.");
}
}
Basketball
public class Basketball extends Game {
@Override
void initialize() {
System.out.println("Basketball Game Initialized.");
}
@Override
void startPlay() {
System.out.println("Basketball Game Started.");
}
@Override
void endPlay() {
System.out.println("Basketball Game Finished.");
}
}
测试类
Client
public class Client {
public static void main(String[] args) {
Game g1 = new Football();
g1.play();
Game g2 = new Basketball();
g2.play();
}
}
public class MIComputerPartVisitor implements ComputerPartVisitor {
@Override
public void visit(Mouse mouse) {
System.out.println("Displaying XiaoMi Mouse ...");
}
@Override
public void visit(Keyboard keyboard) {
System.out.println("Displaying XiaoMi Keyboard ...");
}
}
HPComputerPartVisitor
public class HPComputerPartVisitor implements ComputerPartVisitor {
@Override
public void visit(Mouse mouse) {
System.out.println("Displaying HuiPu Mouse ...");
}
@Override
public void visit(Keyboard keyboard) {
System.out.println("Displaying HuiPu Keyboard ...");
}
}
抽象元素类
ComputerPart
public interface ComputerPart {
void accept(ComputerPartVisitor computerPartVisitor);
}
具体元素类
Mouse
public class Mouse implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
Keyboard
public class Keyboard implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
对象结构类
ObjectStructure
public class ObjectStructure {
private List computerParts = new ArrayList<>();
public void attach(ComputerPart computerPart) {
computerParts.add(computerPart);
}
public void detach(ComputerPart computerPart) {
computerParts.remove(computerPart);
}
public void display(ComputerPartVisitor computerPartVisitor) {
for (ComputerPart computerPart : computerParts) {
computerPart.accept(computerPartVisitor);
}
}
}
最终测试类
Client
public class Client {
public static void main(String[] args) {
ObjectStructure os = new ObjectStructure();
os.attach(new Mouse());
os.attach(new Keyboard());
os.display(new MIComputerPartVisitor());
os.display(new HPComputerPartVisitor());
}
}
public class ConcreteAggregate implements Aggregate {
private List list = new ArrayList<>();
public void add(Object obj) {
list.add(obj);
}
public void remove(Object obj) {
list.remove(obj);
}
public Iterator getIterator() {
return new ConcreteIterator(list);
}
}
最终测试类
Client
public class Client {
public static void main(String[] args) {
Aggregate ag = new ConcreteAggregate();
ag.add("张三");
ag.add("李四");
ag.add("王五");
Iterator it = ag.getIterator();
while (it.hasNext()) {
Object object = it.next();
System.out.println(object.toString());
}
}
}
结果:
张三
李四
王五
4.4、应用
JDK 的 ArrayList 集合中就使用了迭代器模式。
public class ArrayListTest {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("张三");
list.add("李四");
list.add("王五");
Iterator it = list.iterator();
while (it.hasNext()) {
Object object = it.next();
System.out.println(object);
}
}
}
public class Weather {
private float temperature; //温度
private float humidity; //湿度
private float pressure; //压力
public Weather() {}
public Weather(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
}
public float getTemperature() {
return temperature;
}
public void setTemperature(float temperature) {
this.temperature = temperature;
}
public float getHumidity() {
return humidity;
}
public void setHumidity(float humidity) {
this.humidity = humidity;
}
public float getPressure() {
return pressure;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
}
WeatherObservable
import java.util.Observable;
public class WeatherObservable extends Observable {
private Weather weather;
public Weather getWeather() {
return weather;
}
public void setWeather(Weather weather) {
this.weather = weather;
setChanged();
notifyObservers(weather);
}
}
具体观察者
WebSite1
import java.util.Observable;
import java.util.Observer;
public class WebSite1 implements Observer {
private Weather weather;
public void display() {
System.out.println("***** WebSite1 *****");
System.out.println("温度:" + weather.getTemperature());
System.out.println("湿度:" + weather.getHumidity());
System.out.println("压力:" + weather.getPressure());
System.out.println("********************");
}
@Override
public void update(Observable o, Object arg) {
this.weather = (Weather) arg;
display();
}
}
WebSite2
import java.util.Observable;
import java.util.Observer;
public class WebSite2 implements Observer {
private Weather weather;
public void display() {
System.out.println("***** WebSite2 *****");
System.out.println("温度:" + weather.getTemperature());
System.out.println("湿度:" + weather.getHumidity());
System.out.println("压力:" + weather.getPressure());
System.out.println("********************");
}
@Override
public void update(Observable o, Object arg) {
this.weather = (Weather) arg;
display();
}
}
最终测试类
Client
public class Client {
public static void main(String[] args) {
WeatherObservable wo = new WeatherObservable();
wo.addObserver(new WebSite1());
wo.addObserver(new WebSite2());
wo.setWeather(new Weather(10f, 100f, 30.3f));
}
}
public abstract class Mediator {
public abstract void register(Colleague colleague);
public abstract void relay(Colleague colleague);
}
具体中介者
ConcreteMediator
public class ConcreteMediator extends Mediator {
private List colleagues = new ArrayList<>();
public void register(Colleague colleague) {
if (!colleagues.contains(colleague)) {
colleagues.add(colleague);
colleague.setMediator(this);
}
}
public void relay(Colleague colleague) {
for (Colleague c : colleagues) {
if (!c.equals(colleague)) {
((Colleague) c).receive();
}
}
}
}
抽象同事类
Colleague
public abstract class Colleague {
protected Mediator mediator;
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public abstract void receive();
public abstract void send();
}
具体同事类
ConcreteColleague1
public class ConcreteColleague1 extends Colleague {
public void receive() {
System.out.println("具体同事类1收到请求...");
}
public void send() {
System.out.println("具体同事类1发出请求...");
mediator.relay(this); //请中介者转发
}
}
ConcreteColleague2
public class ConcreteColleague2 extends Colleague {
public void receive() {
System.out.println("具体同事类2收到请求...");
}
public void send() {
System.out.println("具体同事类2发出请求...");
mediator.relay(this); //请中介者转发
}
}
最终测试类
Client
public class Client {
public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();
Colleague c1 = new ConcreteColleague1();
Colleague c2 = new ConcreteColleague2();
mediator.register(c1);
mediator.register(c2);
c1.send();
c2.send();
}
}
public class Originator {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Memento createMemento() {
return new Memento(state);
}
public void restoreMemento(Memento memento) {
this.state = memento.getState();
}
}
备忘录
Memento
public class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
管理者
Caretaker
public class Caretaker {
private List mementoList = new ArrayList<>();
public void add(Memento memento) {
mementoList.add(memento);
}
public Memento get(int index) {
return mementoList.get(index);
}
}
测试类
Client
public class Client {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.setState(" 状态#1 攻击力 300 ");
caretaker.add(originator.createMemento());
originator.setState(" 状态#2 攻击力 200 ");
caretaker.add(originator.createMemento());
originator.setState(" 状态#3 攻击力 100 ");
caretaker.add(originator.createMemento());
System.out.println("当前的状态是:" + originator.getState());
originator.restoreMemento(caretaker.get(0));
System.out.println("当前的状态是:" + originator.getState());
}
}
public abstract class Expression {
public abstract int interpreter(HashMap var);
}
终结符表达式
VarExpression
public class VarExpression extends Expression {
private String key;
public VarExpression(String key) {
this.key = key;
}
@Override
public int interpreter(HashMap var) {
return var.get(this.key);
}
}
非终结符表达式
SymbolExpression
public class SymbolExpression extends Expression {
protected Expression left;
protected Expression right;
public SymbolExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public int interpreter(HashMap var) {
return 0;
}
}
环境类
Calculator
public class Calculator {
private Expression expression;
private Expression left;
private Expression right;
public Calculator(String expStr) {
Stack stack = new Stack<>();
char[] charArray = expStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
switch (charArray[i]) {
case '+':
left = stack.pop();
right = new VarExpression(String.valueOf(charArray[++i]));
stack.push(new AddExpression(left, right));
break;
case '-':
left = stack.pop();
right = new VarExpression(String.valueOf(charArray[++i]));
stack.push(new SubExpression(left, right));
break;
default:
stack.push(new VarExpression(String.valueOf(charArray[i])));
break;
}
}
this.expression = stack.pop();
}
public int run(HashMap var) {
return this.expression.interpreter(var);
}
}
测试类
Client
public class Client {
public static void main(String[] args) throws IOException {
String expStr = getExpStr();
HashMap expVal = getValue(expStr);
System.out.println("最终运算结果:" + expStr + "=" + new Calculator(expStr).run(expVal));
}
public static String getExpStr() throws IOException {
System.out.print("请输入表达式:");
return (new BufferedReader(new InputStreamReader(System.in))).readLine();
}
public static HashMap getValue(String expStr) throws IOException {
HashMap map = new HashMap<>();
for (char ch : expStr.toCharArray()) {
if (ch != '+' && ch != '-') {
if (!map.containsKey(String.valueOf(ch))) {
System.out.print("请输入" + String.valueOf(ch) + "的值:");
String value = (new BufferedReader(new InputStreamReader(System.in))).readLine();
map.put(String.valueOf(ch), Integer.valueOf(value));
}
}
}
return map;
}
}
public class Context {
private State state;
public Context() {
this.state = new ConcreteStateA();
}
//设置状态
public void setState(State state) {
this.state = state;
}
//读取状态
public State getState() {
return (state);
}
//请求处理
public void Handle() {
state.Handle(this);
}
}
抽象状态类
State
public abstract class State {
public abstract void Handle(Context context);
}
具体状态类
ConcreteStateA
public class ConcreteStateA extends State {
public void Handle(Context context) {
System.out.println("当前状态是 A.");
context.setState(new ConcreteStateB());
}
}
ConcreteStateB
public class ConcreteStateB extends State {
public void Handle(Context context) {
System.out.println("当前状态是 B.");
context.setState(new ConcreteStateA());
}
}
测试类
Client
public class Client {
public static void main(String[] args) {
Context context = new Context();
context.Handle();
context.Handle();
context.Handle();
context.Handle();
}
}
责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
10.2、关系依赖图
10.3、代码实现
采购员采购教学器材,请设计程序完成采购审批项目。
如果金额小于等于 5000,由主任审批 (0<=x<=5000)
如果金额小于等于 10000,由院长审批(5000
如果金额小于等于 30000,由副校长审批(10000
如果金额超过 30000 以上,有校长审批(30000
抽象处理者
Approver
public abstract class Approver {
protected Approver approver;
protected String name;
public Approver(String name) {
this.name = name;
}
public Approver getNext() {
return approver;
}
public void setNext(Approver approver) {
this.approver = approver;
}
public abstract void handleRequest(PurchaseRequest purchaseRequest);
}
具体处理者
DepartmentApprover
//主任审批
public class DepartmentApprover extends Approver {
public DepartmentApprover(String name) {
super(name);
}
@Override
public void handleRequest(PurchaseRequest purchaseRequest) {
if (purchaseRequest.getPrice() < 0 && purchaseRequest.getPrice() <= 5000) {
System.out.println("本次采购请求被 " + this.name + " 处理");
} else {
if (this.approver != null) {
approver.handleRequest(purchaseRequest);
}
}
}
}
DeanApprover
//院长审批
public class DeanApprover extends Approver {
public DeanApprover(String name) {
super(name);
}
@Override
public void handleRequest(PurchaseRequest purchaseRequest) {
if (purchaseRequest.getPrice() < 5000 && purchaseRequest.getPrice() <= 10000) {
System.out.println("本次采购请求被 " + this.name + " 处理");
} else {
if (this.approver != null) {
approver.handleRequest(purchaseRequest);
}
}
}
}
ViceSchoolMasterApprover
//副校长审批
public class ViceSchoolMasterApprover extends Approver {
public ViceSchoolMasterApprover(String name) {
super(name);
}
@Override
public void handleRequest(PurchaseRequest purchaseRequest) {
if (purchaseRequest.getPrice() < 10000 && purchaseRequest.getPrice() <= 30000) {
System.out.println("本次采购请求被 " + this.name + " 处理");
} else {
if (this.approver != null) {
approver.handleRequest(purchaseRequest);
}
}
}
}
SchoolMasterApprover
//校长审批
public class SchoolMasterApprover extends Approver {
public SchoolMasterApprover(String name) {
super(name);
}
@Override
public void handleRequest(PurchaseRequest purchaseRequest) {
if (purchaseRequest.getPrice() > 30000) {
System.out.println("本次采购请求被 " + this.name + " 处理");
} else {
if (this.approver != null) {
approver.handleRequest(purchaseRequest);
}
}
}
}
最终测试类
Client
public class Client {
public static void main(String[] args) {
//创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(31000);
//创建审批人员
DepartmentApprover departmentApprover = new DepartmentApprover("张主任");
DeanApprover deanApprover = new DeanApprover("李院长");
ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("王副校");
SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("赵校长");
//设置审批链
departmentApprover.setNext(deanApprover);
deanApprover.setNext(viceSchoolMasterApprover);
viceSchoolMasterApprover.setNext(schoolMasterApprover);
//开始处理请求
departmentApprover.handleRequest(purchaseRequest);
}
}
public class Arrays{
public static void sort(T[] a, Comparator super T> c) {
if (c == null) {
//若没有传入Comparator接口的实现类对象,调用默认的升序排序方法
sort(a);
} else {
if (LegacyMergeSort.userRequested)
//jdk5及之前的传统归并排序,新版本中LegacyMergeSort.userRequested默认false
legacyMergeSort(a, c);
else
//改进后的归并排序
TimSort.sort(a, 0, a.length, c, null, 0, 0);
}
}
}
此时我们需要传入两个参数:一个是待排序的数组,另一个则是Comparator接口的实现类对象。其中,Comparator接口是一种函数式接口,该接口中定义了一个抽象方法int compare(T o1, T o2),用于定义具体的排序规则。这里Comparator接口就是策略模式中的抽象策略接口,它定义了一个排序算法,而具体策略(具体的排序算法)将由用户来定义,那么Arrays就是一个环境类,sort() 方法可以传入一个策略c ,让Arrays根据这个策略进行排序任务。
public class demo {
public static void main(String[] args) {
Integer[] data = {12, 2, 3, 2, 4, 5, 1};
// 实现降序排序
Arrays.sort(data, new Comparator() {
// 排序策略 降序
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(Arrays.toString(data)); //[12, 5, 4, 3, 2, 2, 1]
}
}
class TimSort {
static void sort(T[] a, int lo, int hi, Comparator super T> c,
T[] work, int workBase, int workLen) {
assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;
int nRemaining = hi - lo;
if (nRemaining < 2)
return; // Arrays of size 0 and 1 are always sorted
// If array is small, do a "mini-TimSort" with no merges
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
binarySort(a, lo, hi, lo + initRunLen, c);
return;
}
...
}
private static int countRunAndMakeAscending(T[] a, int lo, int hi,Comparator super T> c) {
assert lo < hi;
int runHi = lo + 1;
if (runHi == hi)
return 1;
// Find end of run, and reverse range if descending
if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
runHi++;
}
return runHi - lo;
}
}
public class OcuppyMoreThanHalf {
/**
* Q74 数组中有一个数字出现的次数超过了数组长度的一半,找出这个数字
* two solutions:
* 1.O(n)
* see <beauty of coding>--每次删除两个不同的数字,不改变数组的特性
* 2.O(nlogn)
* 排序。中间
cygwin很多命令显示command not found的解决办法
修改cygwin.BAT文件如下
@echo off
D:
set CYGWIN=tty notitle glob
set PATH=%PATH%;d:\cygwin\bin;d:\cygwin\sbin;d:\cygwin\usr\bin;d:\cygwin\usr\sbin;d:\cygwin\us