├── README.md └── src └── com └── design ├── adapter ├── AdvanceMediaPlayer.java ├── AudioPlayer.java ├── Demo.java ├── MediaAdapter.java ├── MediaPlayer.java ├── Mp4Player.java ├── VlcPlayer.java └── classadpater │ └── VoltageAdapter.java ├── builder └── entity │ ├── Entity1.java │ ├── Entity2.java │ └── Product.java ├── command ├── ex1 │ ├── Main.java │ └── Peddler.java └── ex2 │ ├── AppleCommand.java │ └── Command.java ├── composite └── Employee.java ├── cor └── handler │ ├── Director.java │ ├── PriceHandler.java │ └── Sales.java ├── decorator ├── Client.java └── ICar.java ├── facade ├── Rectangle.java ├── Shape.java ├── ShapeFacade.java └── Square.java ├── factory ├── abstractfactory │ ├── Factory.java │ ├── IProductA.java │ ├── IProductB.java │ ├── IProductFactory.java │ ├── ProductA.java │ └── ProductB.java ├── base │ ├── Audi.java │ ├── Byd.java │ └── Car.java ├── factorymethod │ ├── AudiFactory.java │ ├── BydFactory.java │ └── CarFactory.java └── simplefactory │ └── CarFactory.java ├── flyweight ├── Circle.java ├── Shape.java └── ShapeFactory.java ├── observer ├── Observer.java └── Subject.java ├── prototype ├── Circle.java ├── Demo.java ├── Shape.java ├── ShapeCache.java └── Square.java ├── proxy ├── Car.java ├── Car2.java ├── Car3.java ├── Moveable.java ├── jdkProxy │ ├── Test.java │ └── TimeHandler.java └── staticProxy │ └── CarNoProxy.java ├── singleton ├── HungrySingleton.java ├── InnerClassSingleton.java ├── LazySingleton.java └── SynchronizedSingleton.java ├── strategy ├── AllLowerCaseStrategy.java ├── IsNumericStrategy.java ├── ValidationStrategy.java └── Validator.java └── template ├── BankTemplateMethod.java └── TestClient.java /README.md: -------------------------------------------------------------------------------- 1 | # java-design-patterns 2 | 设计模式 3 | 4 | ----------------------- 5 | ## 目录 6 | 7 | - [Singleton](/src/com/design/singleton/):单例模式 8 | - [Factory](/src/com/design/factory/):工厂模式 9 | - [Strategy](src/com/design/strategy/):策略模式 10 | - [Observer](src/com/design/observer/):观察者模式 11 | - [Template](src/com/design/template/):模板方法模式 12 | - [Proxy](src/com/design/proxy/):代理模式 13 | - [Decorator](src/com/design/decorator/):装饰器模式 14 | - [Facade](src/com/design/facade/):外观模式 15 | - [Composite](src/com/design/composite): 组合模式 16 | - [Adapter](src/com/design/adapter): 适配器模式 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/com/design/adapter/AdvanceMediaPlayer.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/22. 5 | */ 6 | public interface AdvanceMediaPlayer { 7 | 8 | void playVlc(String fileName); 9 | void playMp4(String fileName); 10 | } 11 | -------------------------------------------------------------------------------- /src/com/design/adapter/AudioPlayer.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | /** 4 | * MediaAdapter mediaAdapter; 5 | */ 6 | public class AudioPlayer implements MediaPlayer { 7 | 8 | MediaAdapter mediaAdapter; 9 | 10 | @Override 11 | public void play(String audioType, String fileName) { 12 | 13 | if(audioType.equalsIgnoreCase("mp3")){ 14 | System.out.println("Playing mp3 file. Name: "+ fileName); 15 | } 16 | 17 | else if(audioType.equalsIgnoreCase("vlc") 18 | || audioType.equalsIgnoreCase("mp4")){ 19 | mediaAdapter = new MediaAdapter(audioType); 20 | mediaAdapter.play(audioType, fileName); 21 | } 22 | else{ 23 | System.out.println("Invalid media. "+ 24 | audioType + " format not supported"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/design/adapter/Demo.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | public class Demo { 4 | 5 | public static void main(String[] args) { 6 | AudioPlayer audioPlayer = new AudioPlayer(); 7 | 8 | audioPlayer.play("mp3", "beyond the horizon.mp3"); 9 | audioPlayer.play("mp4", "alone.mp4"); 10 | audioPlayer.play("vlc", "far far away.vlc"); 11 | audioPlayer.play("avi", "mind me.avi"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/design/adapter/MediaAdapter.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | /** 4 | * 适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。 5 | */ 6 | public class MediaAdapter implements MediaPlayer { 7 | 8 | AdvanceMediaPlayer advanceMusicPlayer; 9 | 10 | public MediaAdapter(String audioType){ 11 | if(audioType.equalsIgnoreCase("vlc") ){ 12 | advanceMusicPlayer = new VlcPlayer(); 13 | } else if (audioType.equalsIgnoreCase("mp4")){ 14 | advanceMusicPlayer = new Mp4Player(); 15 | } 16 | } 17 | 18 | @Override 19 | public void play(String audioType, String fileName) { 20 | if(audioType.equalsIgnoreCase("vlc")){ 21 | advanceMusicPlayer.playVlc(fileName); 22 | }else if(audioType.equalsIgnoreCase("mp4")){ 23 | advanceMusicPlayer.playMp4(fileName); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/com/design/adapter/MediaPlayer.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | /** 4 | * MediaPlayer 播放器接口 5 | */ 6 | public interface MediaPlayer { 7 | 8 | void play(String audioType, String fileName); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/design/adapter/Mp4Player.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/22. 5 | */ 6 | public class Mp4Player implements AdvanceMediaPlayer { 7 | 8 | 9 | @Override 10 | public void playVlc(String fileName) { 11 | //doNothing 12 | } 13 | 14 | @Override 15 | public void playMp4(String fileName) { 16 | System.out.println("Playing mp4 file. Name: "+ fileName); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/design/adapter/VlcPlayer.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/22. 5 | */ 6 | public class VlcPlayer implements AdvanceMediaPlayer { 7 | 8 | 9 | @Override 10 | public void playVlc(String fileName) { 11 | System.out.println("Playing vlc file. Name: "+ fileName); 12 | } 13 | 14 | @Override 15 | public void playMp4(String fileName) { 16 | //doNothing 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/design/adapter/classadpater/VoltageAdapter.java: -------------------------------------------------------------------------------- 1 | package com.design.adapter.classadpater; 2 | 3 | /** 4 | * 适配器 5 | */ 6 | public class VoltageAdapter extends Voltage220V implements Voltage5V { 7 | 8 | @Override 9 | public int output5V() { 10 | int voltage = super.output220V(); 11 | int target = voltage / 44; 12 | return target; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/com/design/builder/entity/Entity1.java: -------------------------------------------------------------------------------- 1 | package com.design.builder.entity; 2 | 3 | /** 4 | * Created by Administrator on 2018/3/5. 5 | */ 6 | public class Entity1 { 7 | } 8 | -------------------------------------------------------------------------------- /src/com/design/builder/entity/Entity2.java: -------------------------------------------------------------------------------- 1 | package com.design.builder.entity; 2 | 3 | /** 4 | * Created by Administrator on 2018/3/5. 5 | */ 6 | public class Entity2 { 7 | } 8 | -------------------------------------------------------------------------------- /src/com/design/builder/entity/Product.java: -------------------------------------------------------------------------------- 1 | package com.design.builder.entity; 2 | 3 | /** 4 | * Created by Administrator on 2018/3/5. 5 | */ 6 | public class Product { 7 | 8 | Entity1 entity1; 9 | Entity2 entity2; 10 | } 11 | -------------------------------------------------------------------------------- /src/com/design/command/ex1/Main.java: -------------------------------------------------------------------------------- 1 | package com.design.command.ex1; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/6. 5 | */ 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | Peddler p = new Peddler(); 10 | p.sailApple(); 11 | p.sailBanana(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/design/command/ex1/Peddler.java: -------------------------------------------------------------------------------- 1 | package com.design.command.ex1; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/6. 5 | */ 6 | public class Peddler { 7 | 8 | public void sailApple(){ 9 | System.out.println("卖苹果"); 10 | } 11 | 12 | public void sailBanana(){ 13 | System.out.println("卖香蕉"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/com/design/command/ex2/AppleCommand.java: -------------------------------------------------------------------------------- 1 | package com.design.command.ex2; 2 | 3 | import com.design.command.ex1.Peddler; 4 | 5 | /** 6 | * Created by gegf on 2018/2/7. 7 | */ 8 | public class AppleCommand extends Command { 9 | 10 | public AppleCommand(Peddler peddler) { 11 | super(peddler); 12 | } 13 | 14 | @Override 15 | public void sail() { 16 | this.getPeddler().sailApple(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/com/design/command/ex2/Command.java: -------------------------------------------------------------------------------- 1 | package com.design.command.ex2; 2 | 3 | import com.design.command.ex1.Peddler; 4 | 5 | /** 6 | * Created by gegf on 2018/2/7. 7 | */ 8 | public abstract class Command { 9 | 10 | private Peddler peddler; 11 | 12 | public Command(Peddler peddler) { 13 | super(); 14 | this.peddler = peddler; 15 | } 16 | 17 | public Peddler getPeddler() { 18 | return peddler; 19 | } 20 | 21 | public void setPeddler(Peddler peddler) { 22 | this.peddler = peddler; 23 | } 24 | 25 | public abstract void sail(); 26 | } 27 | -------------------------------------------------------------------------------- /src/com/design/composite/Employee.java: -------------------------------------------------------------------------------- 1 | package com.design.composite; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。 8 | * 9 | */ 10 | public class Employee { 11 | private String name; 12 | private String dept; 13 | private int salary; 14 | 15 | // Employee 类,该类带有 Employee 对象的列表。 16 | private List subordinates; 17 | 18 | public Employee(String name,String dept, int sal) { 19 | this.name = name; 20 | this.dept = dept; 21 | this.salary = sal; 22 | subordinates = new ArrayList(); 23 | } 24 | 25 | public void add(Employee e) { 26 | subordinates.add(e); 27 | } 28 | 29 | public void remove(Employee e) { 30 | subordinates.remove(e); 31 | } 32 | 33 | public List getSubordinates(){ 34 | return subordinates; 35 | } 36 | 37 | public String toString(){ 38 | return ("Employee :[ Name : "+ name 39 | +", dept : "+ dept + ", salary :" 40 | + salary+" ]"); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/com/design/cor/handler/Director.java: -------------------------------------------------------------------------------- 1 | package com.design.cor.handler; 2 | 3 | public class Director extends PriceHandler { 4 | 5 | @Override 6 | public void processDiscount(float discount) { 7 | if (discount <= 0.4) { 8 | System.out.format("%s批准了:%。2f%n", this.getClass(), discount); 9 | } else { 10 | successor.processDiscount(discount); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/design/cor/handler/PriceHandler.java: -------------------------------------------------------------------------------- 1 | package com.design.cor.handler; 2 | 3 | /** 4 | * 价格处理人,负责处理折扣申请的抽象类 5 | */ 6 | public abstract class PriceHandler { 7 | 8 | /** 9 | * 直接上级,用于传递请求,无权限处理时交给上级处理 10 | */ 11 | protected PriceHandler successor; //采用链表接口,指向自身引用, 12 | 13 | public void setSuccessor(PriceHandler priceHandler){ 14 | this.successor = successor; 15 | } 16 | 17 | public abstract void processDiscount(float discount); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/com/design/cor/handler/Sales.java: -------------------------------------------------------------------------------- 1 | package com.design.cor.handler; 2 | 3 | /** 4 | * SE 可批准5%内的折扣 5 | */ 6 | public class Sales extends PriceHandler { 7 | 8 | @Override 9 | public void processDiscount(float discount) { 10 | if(discount <= 0.05){ 11 | System.out.format("%s批准了折扣:%2.f%n", this.getClass().getName(), discount); 12 | }else { 13 | successor.processDiscount(discount); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/decorator/Client.java: -------------------------------------------------------------------------------- 1 | package com.design.decorator; 2 | 3 | /** 4 | * Created by Administrator on 2018/1/6. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | ICar car = new Car(); 10 | car.move(); 11 | 12 | System.out.println("---增加自动驾驶---"); 13 | AICar aiCar = new AICar(car); 14 | aiCar.move(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/decorator/ICar.java: -------------------------------------------------------------------------------- 1 | package com.design.decorator; 2 | 3 | /** 4 | * Created by Administrator on 2018/1/6. 5 | */ 6 | public interface ICar { 7 | 8 | public void move(); 9 | } 10 | 11 | class Car implements ICar{ 12 | 13 | @Override 14 | public void move() { 15 | System.out.println("car is move..."); 16 | } 17 | } 18 | 19 | //装饰器 20 | class SuperCar implements ICar{ 21 | 22 | private ICar car; 23 | 24 | public SuperCar(ICar car) { 25 | super(); 26 | this.car = car; 27 | } 28 | 29 | @Override 30 | public void move() { 31 | car.move(); 32 | } 33 | } 34 | 35 | //具体装饰角色 36 | class AICar extends SuperCar{ 37 | 38 | public AICar(ICar car) { 39 | super(car); 40 | } 41 | 42 | public void autoMove(){ 43 | System.out.println("自动跑..."); 44 | } 45 | 46 | @Override 47 | public void move() { 48 | super.move(); 49 | autoMove(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/com/design/facade/Rectangle.java: -------------------------------------------------------------------------------- 1 | package com.design.facade; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/8. 5 | */ 6 | public class Rectangle implements Shape { 7 | 8 | @Override 9 | public void draw() { 10 | System.out.println("Rectangle::draw()"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/com/design/facade/Shape.java: -------------------------------------------------------------------------------- 1 | package com.design.facade; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/8. 5 | */ 6 | public interface Shape { 7 | 8 | void draw(); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/design/facade/ShapeFacade.java: -------------------------------------------------------------------------------- 1 | package com.design.facade; 2 | 3 | /** 4 | * 外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。 5 | * 这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。 6 | */ 7 | public class ShapeFacade { 8 | 9 | private Shape rectangle; 10 | private Shape square; 11 | 12 | public ShapeFacade() { 13 | 14 | rectangle = new Rectangle(); 15 | square = new Square(); 16 | } 17 | 18 | public void drawRectangle(){ 19 | rectangle.draw(); 20 | } 21 | public void drawSquare(){ 22 | square.draw(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/design/facade/Square.java: -------------------------------------------------------------------------------- 1 | package com.design.facade; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/8. 5 | */ 6 | public class Square implements Shape { 7 | 8 | @Override 9 | public void draw() { 10 | System.out.println("Square::draw()"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/com/design/factory/abstractfactory/Factory.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/29. 5 | */ 6 | public class Factory implements IProductFactory { 7 | @Override 8 | public IProductA createProductA() { 9 | return new ProductA(); 10 | } 11 | 12 | @Override 13 | public IProductB createProduct() { 14 | return new ProductB(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/factory/abstractfactory/IProductA.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/29. 5 | */ 6 | public interface IProductA { 7 | 8 | public void show(); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/design/factory/abstractfactory/IProductB.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/29. 5 | */ 6 | public interface IProductB { 7 | 8 | public void show(); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/design/factory/abstractfactory/IProductFactory.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/29. 5 | */ 6 | public interface IProductFactory { 7 | 8 | public IProductA createProductA(); 9 | 10 | public IProductB createProduct(); 11 | } 12 | -------------------------------------------------------------------------------- /src/com/design/factory/abstractfactory/ProductA.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/29. 5 | */ 6 | public class ProductA implements IProductA { 7 | @Override 8 | public void show() { 9 | System.out.println("这是A产品"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/com/design/factory/abstractfactory/ProductB.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/29. 5 | */ 6 | public class ProductB implements IProductB { 7 | @Override 8 | public void show() { 9 | System.out.println("这是B产品"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/com/design/factory/base/Audi.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.base; 2 | 3 | /** 4 | * Created by geguofeng on 2017/12/28. 5 | */ 6 | public class Audi implements Car { 7 | 8 | @Override 9 | public void run() { 10 | System.out.println("Audi is running..."); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/com/design/factory/base/Byd.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.base; 2 | 3 | /** 4 | * Created by Administrator on 2017/12/28. 5 | */ 6 | public class Byd implements Car { 7 | 8 | @Override 9 | public void run() { 10 | System.out.println("Byd is running..."); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/com/design/factory/base/Car.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.base; 2 | 3 | /** 4 | * 5 | * Created by geguofeng on 2017/12/28. 6 | */ 7 | public interface Car { 8 | 9 | public void run(); 10 | } 11 | -------------------------------------------------------------------------------- /src/com/design/factory/factorymethod/AudiFactory.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.factorymethod; 2 | 3 | import com.design.factory.base.Audi; 4 | import com.design.factory.base.Car; 5 | 6 | /** 7 | * Created by Administrator on 2017/12/28. 8 | */ 9 | public class AudiFactory implements CarFactory { 10 | @Override 11 | public Car createCar() { 12 | return new Audi(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/com/design/factory/factorymethod/BydFactory.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.factorymethod; 2 | 3 | import com.design.factory.base.Byd; 4 | import com.design.factory.base.Car; 5 | 6 | /** 7 | * Created by Administrator on 2017/12/28. 8 | */ 9 | public class BydFactory implements CarFactory { 10 | @Override 11 | public Car createCar() { 12 | return new Byd(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/com/design/factory/factorymethod/CarFactory.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.factorymethod; 2 | 3 | import com.design.factory.base.Car; 4 | 5 | /** 6 | * Created by geguofeng on 2017/12/28. 7 | */ 8 | public interface CarFactory { 9 | 10 | 11 | public Car createCar(); 12 | } 13 | -------------------------------------------------------------------------------- /src/com/design/factory/simplefactory/CarFactory.java: -------------------------------------------------------------------------------- 1 | package com.design.factory.simplefactory; 2 | 3 | import com.design.factory.base.Audi; 4 | import com.design.factory.base.Byd; 5 | import com.design.factory.base.Car; 6 | 7 | /** 8 | * 工厂类 9 | * Created by geguofeng on 2017/12/28. 10 | */ 11 | public class CarFactory { 12 | 13 | public static Car createCar(String carType){ 14 | if("audi".equals(carType)){ 15 | return new Audi(); 16 | }else if("byd".equals(carType)){ 17 | return new Byd(); 18 | }else{ 19 | return null; 20 | } 21 | } 22 | 23 | public static Car createAudi(){ 24 | return new Audi(); 25 | } 26 | 27 | public static Car createByd(){ 28 | return new Byd(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/design/flyweight/Circle.java: -------------------------------------------------------------------------------- 1 | package com.design.flyweight; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/3. 5 | */ 6 | public class Circle implements Shape { 7 | 8 | private String color; 9 | private int x; 10 | private int y; 11 | private int radius; 12 | 13 | public String getColor() { 14 | return color; 15 | } 16 | 17 | public void setColor(String color) { 18 | this.color = color; 19 | } 20 | 21 | public int getX() { 22 | return x; 23 | } 24 | 25 | public void setX(int x) { 26 | this.x = x; 27 | } 28 | 29 | public int getY() { 30 | return y; 31 | } 32 | 33 | public void setY(int y) { 34 | this.y = y; 35 | } 36 | 37 | public int getRadius() { 38 | return radius; 39 | } 40 | 41 | public void setRadius(int radius) { 42 | this.radius = radius; 43 | } 44 | 45 | public Circle(){} 46 | 47 | public Circle(String color){ 48 | this.color = color; 49 | } 50 | 51 | @Override 52 | public void draw() { 53 | System.out.println("Circle: Draw() [Color : " + color 54 | +", x : " + x +", y :" + y +", radius :" + radius); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/com/design/flyweight/Shape.java: -------------------------------------------------------------------------------- 1 | package com.design.flyweight; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/3. 5 | */ 6 | public interface Shape { 7 | 8 | public void draw(); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/design/flyweight/ShapeFactory.java: -------------------------------------------------------------------------------- 1 | package com.design.flyweight; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * 享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。 7 | * 这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。 8 | */ 9 | public class ShapeFactory { 10 | 11 | private static final HashMap circleMap = new HashMap<>(); 12 | 13 | public static Shape getCircle(String color) { 14 | Circle circle = (Circle)circleMap.get(color); 15 | 16 | if(circle == null) { 17 | circle = new Circle(color); 18 | circleMap.put(color, circle); 19 | System.out.println("Creating circle of color : " + color); 20 | } 21 | return circle; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/design/observer/Observer.java: -------------------------------------------------------------------------------- 1 | package com.design.observer; 2 | 3 | /** 4 | * 观察者 5 | * Created by Administrator on 2018/1/3. 6 | */ 7 | public interface Observer { 8 | 9 | public void update(Subject subject); 10 | } 11 | -------------------------------------------------------------------------------- /src/com/design/observer/Subject.java: -------------------------------------------------------------------------------- 1 | package com.design.observer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 主题对象 8 | * Created by Administrator on 2018/1/3. 9 | */ 10 | 11 | public class Subject { 12 | 13 | private List list = new ArrayList(); 14 | 15 | public void registerObserver(Observer obs){ 16 | list.add(obs); 17 | } 18 | 19 | public void removeObserver(Observer obs){ 20 | list.remove(obs); 21 | } 22 | 23 | public void notifyAllObservers(){ 24 | for (Observer obs : list){ 25 | obs.update(this); 26 | } 27 | } 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/com/design/prototype/Circle.java: -------------------------------------------------------------------------------- 1 | package com.design.prototype; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/2. 5 | */ 6 | public class Circle extends Shape { 7 | 8 | public Circle(){ 9 | this.type = "Circle"; 10 | } 11 | 12 | @Override 13 | void draw() { 14 | System.out.println("Inside Circle::draw() method."); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/prototype/Demo.java: -------------------------------------------------------------------------------- 1 | package com.design.prototype; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/3. 5 | */ 6 | public class Demo { 7 | 8 | public static void main(String[] args) { 9 | ShapeCache.loadCache(); 10 | Shape cloneShape = ShapeCache.getShape(1); 11 | System.out.println(cloneShape.getType()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/com/design/prototype/Shape.java: -------------------------------------------------------------------------------- 1 | package com.design.prototype; 2 | 3 | /** 4 | * 创建一个实现了 Clonable 接口的抽象类 5 | * 6 | * 原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。 7 | 这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。 8 | */ 9 | public abstract class Shape implements Cloneable{ 10 | 11 | private int id; 12 | protected String type; 13 | 14 | abstract void draw(); 15 | 16 | public int getId() { 17 | return id; 18 | } 19 | 20 | public void setId(int id) { 21 | this.id = id; 22 | } 23 | 24 | public String getType() { 25 | return type; 26 | } 27 | 28 | public void setType(String type) { 29 | this.type = type; 30 | } 31 | 32 | @Override 33 | protected Object clone(){ 34 | Object clone = null; 35 | try { 36 | clone = super.clone(); 37 | } catch (CloneNotSupportedException e) { 38 | e.printStackTrace(); 39 | } 40 | return clone; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/com/design/prototype/ShapeCache.java: -------------------------------------------------------------------------------- 1 | package com.design.prototype; 2 | 3 | import java.util.Hashtable; 4 | 5 | /** 6 | * Created by Administrator on 2018/2/2. 7 | */ 8 | public class ShapeCache { 9 | 10 | private static Hashtable shapeMap 11 | = new Hashtable(); 12 | 13 | public static Shape getShape(int shapeId) { 14 | Shape cachedShape = shapeMap.get(shapeId); 15 | return (Shape) cachedShape.clone(); 16 | } 17 | 18 | // 对每种形状都运行数据库查询,并创建该形状 19 | // shapeMap.put(shapeKey, shape); 20 | public static void loadCache() { 21 | Circle circle = new Circle(); 22 | circle.setId(1); 23 | shapeMap.put(circle.getId(),circle); 24 | 25 | Square square = new Square(); 26 | square.setId(2); 27 | shapeMap.put(square.getId(),square); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/design/prototype/Square.java: -------------------------------------------------------------------------------- 1 | package com.design.prototype; 2 | 3 | /** 4 | * Created by Administrator on 2018/2/2. 5 | */ 6 | public class Square extends Shape { 7 | 8 | public Square(){ 9 | this.type = "Square"; 10 | } 11 | 12 | @Override 13 | void draw() { 14 | System.out.println("Inside Square::draw() method."); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/proxy/Car.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * 没有代理的实现方式 7 | * Created by geguofeng on 2017/12/29. 8 | */ 9 | public class Car implements Moveable { 10 | 11 | @Override 12 | public void move() { 13 | //实现开车的过程 14 | try { 15 | Thread.sleep(new Random().nextInt(1000)); 16 | System.out.println("汽车行驶中..."); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/com/design/proxy/Car2.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy; 2 | 3 | /** 4 | * 使用继承的实现方式实现代理 5 | * Created by geguofeng on 2017/12/29. 6 | */ 7 | public class Car2 extends Car { 8 | 9 | @Override 10 | public void move() { 11 | //记录一下汽车行驶的时间 12 | long startTime = System.currentTimeMillis(); 13 | System.out.println("汽车开始行驶..."); 14 | super.move(); 15 | long endTime = System.currentTimeMillis(); 16 | long res = endTime - startTime; 17 | System.out.println("汽车行驶结束...,共行驶"+res+"毫秒"); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Moveable car = new Car2(); 22 | car.move(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/com/design/proxy/Car3.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy; 2 | 3 | /** 4 | * 使用聚合方式实现代理 5 | * Created by geguofeng on 2017/12/29. 6 | */ 7 | public class Car3 implements Moveable{ 8 | 9 | //携带一个car 10 | private Car car; 11 | 12 | public Car3(Car car){ 13 | super(); 14 | this.car = car; 15 | } 16 | 17 | @Override 18 | public void move() { 19 | //记录一下汽车行驶的时间 20 | long startTime = System.currentTimeMillis(); 21 | System.out.println("汽车开始行驶..."); 22 | car.move(); 23 | long endTime = System.currentTimeMillis(); 24 | long res = endTime - startTime; 25 | System.out.println("汽车行驶结束...,共行驶"+res+"毫秒"); 26 | 27 | } 28 | 29 | public static void main(String[] args) { 30 | Car car = new Car(); 31 | Moveable car3 = new Car3(car); 32 | car3.move(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/design/proxy/Moveable.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy; 2 | 3 | /** 4 | * Created by geguofeng on 2017/12/29. 5 | */ 6 | public interface Moveable { 7 | 8 | public void move(); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/design/proxy/jdkProxy/Test.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy.jdkProxy; 2 | 3 | import com.design.proxy.Car; 4 | import com.design.proxy.Moveable; 5 | 6 | import java.lang.reflect.InvocationHandler; 7 | import java.lang.reflect.Proxy; 8 | 9 | /** 10 | * Created by Administrator on 2018/1/3. 11 | */ 12 | public class Test { 13 | 14 | public static void main(String[] args) { 15 | Car car = new Car(); 16 | 17 | InvocationHandler invocationHandler = new TimeHandler(car); 18 | 19 | Class cls = car.getClass(); 20 | 21 | Moveable moveable = (Moveable) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), invocationHandler); 22 | 23 | moveable.move(); 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/com/design/proxy/jdkProxy/TimeHandler.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy.jdkProxy; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | 6 | /** 7 | * Created by Administrator on 2018/1/3. 8 | */ 9 | public class TimeHandler implements InvocationHandler { 10 | 11 | private Object target; 12 | 13 | public TimeHandler(Object target) { 14 | super(); 15 | this.target = target; 16 | } 17 | 18 | /** 19 | * 20 | * @param proxy 被代理的对象 21 | * @param method 被代理对象的方法 22 | * @param args 方法的参数 23 | * @return 方法的返回值 24 | * @throws Throwable 25 | */ 26 | @Override 27 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 28 | long startTime = System.currentTimeMillis(); 29 | System.out.println("汽车开始行驶..."); 30 | method.invoke(target); 31 | long endTime = System.currentTimeMillis(); 32 | long res = endTime - startTime; 33 | System.out.println("汽车行驶结束...,共行驶"+res+"毫秒"); 34 | return null; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/com/design/proxy/staticProxy/CarNoProxy.java: -------------------------------------------------------------------------------- 1 | package com.design.proxy.staticProxy; 2 | 3 | import com.design.proxy.Moveable; 4 | 5 | import java.util.Random; 6 | 7 | /** 8 | * 没有代理的实现方式 9 | * Created by geguofeng on 2017/12/29. 10 | */ 11 | public class CarNoProxy implements Moveable { 12 | 13 | @Override 14 | public void move() { 15 | //记录一下汽车行驶的时间 16 | long startTime = System.currentTimeMillis(); 17 | System.out.println("汽车开始行驶..."); 18 | //实现开车的过程 19 | try { 20 | Thread.sleep(new Random().nextInt(1000)); 21 | System.out.println("汽车行驶中..."); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | long endTime = System.currentTimeMillis(); 26 | long res = endTime - startTime; 27 | System.out.println("汽车行驶结束...,共行驶"+res+"毫秒"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/design/singleton/HungrySingleton.java: -------------------------------------------------------------------------------- 1 | package com.design.singleton; 2 | 3 | /** 4 | * 饿汉式单例模式 5 | * 6 | * Created geguofeng by on 2017/12/27. 7 | */ 8 | public class HungrySingleton { 9 | 10 | //将构造函数私有化,不允许外部对象直接调用 11 | private HungrySingleton(){} 12 | 13 | private static HungrySingleton instance = new HungrySingleton(); 14 | 15 | //对外提供唯一用于获取实例的方法 16 | public static HungrySingleton getInstance(){ 17 | return instance; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/com/design/singleton/InnerClassSingleton.java: -------------------------------------------------------------------------------- 1 | package com.design.singleton; 2 | 3 | /** 4 | * 内部类实现单例模式 5 | * Created by geguofeng on 2017/12/27. 6 | */ 7 | public class InnerClassSingleton { 8 | 9 | public static Singleton getInstance(){ 10 | return Singleton.singleton; 11 | } 12 | 13 | private static class Singleton{ 14 | protected static Singleton singleton = new Singleton(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/com/design/singleton/LazySingleton.java: -------------------------------------------------------------------------------- 1 | package com.design.singleton; 2 | 3 | /** 4 | * 懒汉式单例模式 5 | * (在多线程下不能保证创建的实例是唯一的) 6 | * Created by geguofeng on 2017/12/27. 7 | */ 8 | public class LazySingleton { 9 | 10 | private LazySingleton(){} 11 | 12 | //和饿汉式不同,这里不实例化,而是在需要的时候再去new 13 | private static LazySingleton instance; 14 | 15 | //在多线程下不能保证创建的实例是唯一的 16 | public static LazySingleton getInstance(){ 17 | if(instance==null){ 18 | instance = new LazySingleton(); 19 | } 20 | return instance; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/com/design/singleton/SynchronizedSingleton.java: -------------------------------------------------------------------------------- 1 | package com.design.singleton; 2 | 3 | /** 4 | * 懒汉式改进 线程安全的单例模式 5 | * Created by geguofeng on 2017/12/27. 6 | */ 7 | public class SynchronizedSingleton { 8 | 9 | private SynchronizedSingleton(){} 10 | 11 | //和饿汉式不同,这里不实例化,而是在需要的时候再去new 12 | private static SynchronizedSingleton instance; 13 | 14 | //双重加锁 15 | public static SynchronizedSingleton getInstance(){ 16 | if(instance == null){ 17 | synchronized (SynchronizedSingleton.class){ 18 | if(instance == null){ 19 | instance = new SynchronizedSingleton(); 20 | } 21 | } 22 | } 23 | return instance; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/com/design/strategy/AllLowerCaseStrategy.java: -------------------------------------------------------------------------------- 1 | package com.design.strategy; 2 | 3 | /** 4 | * 策略1: 是否都是小写 5 | * @author geguofeng 6 | * 7 | */ 8 | public class AllLowerCaseStrategy implements ValidationStrategy { 9 | 10 | @Override 11 | public boolean validate(String str) { 12 | return str.matches("[a-z]+"); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/com/design/strategy/IsNumericStrategy.java: -------------------------------------------------------------------------------- 1 | package com.design.strategy; 2 | 3 | /** 4 | * 策略2:验证是否是数字 5 | * @author geguofeng 6 | * 7 | */ 8 | public class IsNumericStrategy implements ValidationStrategy { 9 | 10 | @Override 11 | public boolean validate(String str) { 12 | 13 | return str.matches("\\d+"); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/strategy/ValidationStrategy.java: -------------------------------------------------------------------------------- 1 | package com.design.strategy; 2 | /** 3 | * 策略模式代表了解决一类算法的通用解决方案,你可以在运行时选择使用哪种方案。 4 | * @author geguofeng 5 | * 策略接口 6 | */ 7 | public interface ValidationStrategy { 8 | 9 | /** 10 | * 验证字符串是否符合规则 11 | * @param str 12 | * @return 13 | */ 14 | public boolean validate(String str); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/com/design/strategy/Validator.java: -------------------------------------------------------------------------------- 1 | package com.design.strategy; 2 | 3 | /** 4 | * 测试类 5 | * @author geguofeng 6 | * 7 | */ 8 | public class Validator { 9 | 10 | private ValidationStrategy validationStrategy; 11 | 12 | //携带一个策略 13 | public Validator(ValidationStrategy validationStrategy){ 14 | this.validationStrategy = validationStrategy; 15 | } 16 | 17 | public Boolean exec(String str){ 18 | return this.validationStrategy.validate(str); 19 | } 20 | 21 | public static void main(String[] args) { 22 | Validator validatorA = new Validator(new AllLowerCaseStrategy()); 23 | System.out.println(validatorA.exec("aaaa")); 24 | Validator validatorB = new Validator(new IsNumericStrategy()); 25 | System.out.println(validatorB.exec("123")); 26 | 27 | //使用Java8 Lamdba表达式重构 28 | Validator validatorC = new Validator((String s) -> s.matches("[a-z]+")); 29 | System.out.println(validatorC.exec("bbb")); 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/com/design/template/BankTemplateMethod.java: -------------------------------------------------------------------------------- 1 | package com.design.template; 2 | 3 | /** 4 | * 抽象基类 定义算法框架,以银行业务为模板 5 | * * Created by Administrator on 2018/1/3. 6 | */ 7 | public abstract class BankTemplateMethod { 8 | 9 | /** 10 | * 具体方法 11 | */ 12 | public void takeNumber(){ 13 | System.out.println("取号排队"); 14 | } 15 | 16 | public abstract void transact(); //具体业务方法 17 | 18 | public void evaluate(){ 19 | System.out.println("反馈评分"); 20 | } 21 | 22 | public final void process(){ 23 | this.takeNumber(); 24 | transact(); //回调 25 | this.evaluate(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/design/template/TestClient.java: -------------------------------------------------------------------------------- 1 | package com.design.template; 2 | 3 | /** 4 | * Created by Administrator on 2018/1/4. 5 | */ 6 | public class TestClient { 7 | 8 | public static void main(String[] args) { 9 | BankTemplateMethod btm = new DrawMoney(); 10 | btm.process(); 11 | 12 | //2.采用匿名内部类 13 | BankTemplateMethod btm2 = new BankTemplateMethod() { 14 | @Override 15 | public void transact() { 16 | System.out.println("我要存款"); 17 | } 18 | }; 19 | btm2.process(); 20 | 21 | } 22 | } 23 | 24 | //1.定义子类 25 | class DrawMoney extends BankTemplateMethod{ 26 | 27 | @Override 28 | public void transact() { 29 | System.out.println("我要取款!"); 30 | } 31 | } 32 | --------------------------------------------------------------------------------