來自阿里Java架構師的十三份設計模式筆記

一、單例模式

定義:確保一個類只有一個實例,並提供一個全局訪問點。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
public static Singleton getInstance() {
if(instance == null){
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
}
/<code>

二、工廠模式

定義:工廠模式定義了一個創建對象的接口,由子類決定要實例化的類是哪一個。工廠方法讓類把實例化推遲到子類。

2.1 簡單工廠模式

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public abstract class Product {
public void method1() {
}
public void method2() {
}
}
public class Product_A extends Product{
public Product_A() {
}
public void method1() {
System.out.println("this is method1 in Product_A");
}
public void method2() {
System.out.println("this is method2 in Product_A");
}
}
public class Product_B extends Product{
public Product_B() {
}
public void method1() {
System.out.println("this is method1 in Product_B");
}
public void method2() {
System.out.println("this is method2 in Product_B");
}
}
public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
public static Singleton getInstance() {
if(instance == null){
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
}
/<code>

2.2 抽象工廠模式

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface Product {
public void method1();
public void method2();
}
public class Product_A implements Product {
@Override
public void method1() {
System.out.println("this is method1 in Product_A");
}
@Override
public void method2() {
System.out.println("this is method2 in Product_A");
}
}
public class Product_B implements Product {

@Override
public void method1() {
System.out.println("this is method1 in Product_B");
}
@Override
public void method2() {
System.out.println("this is method2 in Product_B");
}
}
public interface AbstractFactory {
public Product getProduct();
}
public class Product_A_Factoty implements AbstractFactory {
@Override
public Product getProduct() {
return new Product_A();
}
}
public class Product_B_Factory implements AbstractFactory {
@Override
public Product getProduct() {
return new Product_B();
}
}
/<code>

三、策略模式

定義:策略模式定義了算法族,分別將其封裝起來,讓它們之間可以相互替換,此模式讓算法的變化獨立於使用算法的客戶。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public abstract class Processor {
public Object process(Object obj){
return obj;
}
}
/**
* ConcreteProcessor
* */
public class Upcase extends Processor{
public String process(Object obj){
return ((String)obj).toUpperCase();
}
}
/**
* ConcreteProcessor
* */
public class Downcase extends Processor{
public String process(Object obj){
return ((String)obj).toLowerCase();
}
}
public class Strategy {
public void process(Processor p,Object obj) {
System.out.println(p.process(obj));
}
}
/<code>

四、觀察者模式

定義:觀察者模式定義了對象之間的一對多依賴,這樣一來,當一個對象改變狀態時,它的所有依賴者都會收到通知並自動更新。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObserver();
//當主題狀態改變時,該方法會被調用,以通知所有的觀察者
}
public class ConcreteSubject implements Subject {
private List<observer> observers;
private String parameter;
public ConcreteSubject() {
this.observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer o) {
this.observers.add(o);
}
@Override
public void removeObserver(Observer o) {
this.observers.remove(o);
}
@Override
public void notifyObserver() {
int i,n;
n = this.observers.size();
for (i = 0;i < n;i++){
Observer observer = this.observers.get(i);
observer.update(parameter);
}
}
public void setParameter(String parameter) {
this.parameter = parameter;
notifyObserver();
}
}
public interface Observer {
public void update(String parameter);
}
public class ConcreteObserver implements Observer {
private String parameter;
private Subject subject;
public ConcreteObserver(Subject subject) {
this.subject = subject;
this.subject.registerObserver(this);

}
@Override
public void update(String parameter) {
this.parameter = parameter;
display();
}
public void display() {
System.out.println("Current state : " + parameter);
}
}
/<observer>/<code>

五、裝飾者模式

定義:動態地將責任附加到對象上。若要擴展功能,裝飾著提供了比繼承更有彈性的替代方法。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public abstract class Component {
protected String description = "Component";
public String getDescription() {
return description;
}
}
public class ConcreteComponent_A extends Component{
public ConcreteComponent_A() {
description = "ConcreteComponent_A";
}
public String getDescription() {
return description;
}
}
public class ConcreteComponent_B extends Component{
public ConcreteComponent_B() {
description = "ConcreteComponent_B";
}
public String getDescription() {
return description;
}
}
public abstract class Decorator extends Component{
public abstract String getDescription();
}
public class ConcreteDecorator_A extends Decorator{
Component component;
public ConcreteDecorator_A(Component component) {
this.component = component;
}
@Override
public String getDescription() {
return component.getDescription() + ", ConcreteDecorator_A";
}
}
public class ConcreteDecorator_B extends Decorator{
Component component;
public ConcreteDecorator_B(Component component) {
this.component = component;
}
@Override
public String getDescription() {
return component.getDescription() + ", ConcreteDecorator_B";
}
}
/<code>

六、命令模式

定義:將“請求”封裝成對象,以便使用不同的請求、隊列或日誌來參數化其對象。命令模式也支持可撤銷的操作。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface Command {
public void execute();
}
/** 起到ConcreteCommand的作用

* */
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
/** 起到ConcreteCommand的作用
* */
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
/** 起到Receiver的作用
* */
public class Light {
private Boolean light;
private String name;
public Light(String name) {
this.name = name;
}
public void on() {
light = true;
}
public void off() {
light = false;
}
@Override
public String toString() {
return "Light [name = " + name + ", is = " + light + "]";
}
}
public class Invoker {
private Command[] onCommands;
private Command[] offCommands;
public Invoker() {
onCommands = new Command[2];
offCommands = new Command[2];
for (int i = 0;i < 2;i++){

onCommands[i] = null;
offCommands[i] = null;
}
}
public void setCommand(int index,Command on,Command off) {
onCommands[index] = on;
offCommands[index] = off;
}
public void onButtonWasPushed(int index) {
onCommands[index].execute();
}
public void offButtonWasPushed(int index) {
offCommands[index].execute();
}
@Override
public String toString() {
String str = "";
for (int i = 0;i < onCommands.length;i++){
str += "index "+i+" : "+onCommands[i].getClass().getName()+" "+offCommands[i].getClass().getName()+"n";
}
return str;
}
}
/<code>

七、適配器模式

定義:將一個類的接口,轉換成客戶期望的另一個接口。適配器讓原本接口不兼容的類可以合作無間。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface Target {
public void request();
}
public class RealTarget implements Target {
@Override
public void request() {
System.out.println("this is real do.");
}
}
public class Adaptee {
public void doing() {
System.out.println("this is Adaptee_do.");
}
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.doing();
}
}
/<code>

八、外觀模式

定義:提供了一個統一的接口,用來訪問子系統中的一群接口。外觀定義了一個高層接口,讓子系統更容易使用。

類圖:

來自阿里Java架構師的十三份設計模式筆記

九、模板方法模式

定義:在一個方法中定義一個算法的骨架,而將一些步驟延遲到子類中。模板方法使得子類可以在不改變算法結構的情況下,重新定義算法中的某些步驟。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public abstract class AbstractClass { 

final void templateMethod(){
primitiveOperation1();
primitiveOperation2();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
}
public class ConcreteClass_A extends AbstractClass{
@Override
void primitiveOperation1() {
System.out.println("this is primitiveOperation1 in ConcreteClass_A");
}
@Override
void primitiveOperation2() {
System.out.println("this is primitiveOperation2 in ConcreteClass_A");
}
}
public class ConcreteClass_B extends AbstractClass{
@Override
void primitiveOperation1() {
System.out.println("this is primitiveOperation1 in ConcreteClass_B");
}
@Override
void primitiveOperation2() {
System.out.println("this is primitiveOperation2 in ConcreteClass_B");
}
}
/<code>

十、迭代器模式

定義:提供一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。

作用:迭代器模式讓我們能遊走於聚合內的每一個元素,而又不暴露其內部的表示。將遊走的任務放在迭代器上,而不是聚合上,這樣簡化了聚合的接口和實現,也讓責任各得其所。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface Aggregate {
public Iterator createIterator();
//我們使用java.util.Iterator作為Iterator類
}
public class ConcreteAggregate implements Aggregate {
List list;
public ConcreteAggregate() {
this.list = new ArrayList();
init();
}
public void init() {
addItem("first");
addItem("second");
addItem("third");
}
public void addItem(String parameter) {
list.add(parameter);
}

@Override
public Iterator createIterator() {
return list.iterator();
}
}
/<code>

十一、組合模式

定義:允許將對象組合成樹形結構來表現“整體/部分”層次結構。

作用:組合能讓客戶以一致的方式處理個別對象以及對象組合。組合模式讓我們能用樹形方式創建對象的結構,樹中包含了組合以及個別的對象。使用組合結構,我們能把相同的操作應用在組合和個別對象上。換句話說,在大多數情況下,我們可以忽略對象組合和個別對象之間的差異。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public abstract class Component {
public void add(Component component) {
throw new UnsupportedOperationException();
}
public void remove(Component component) {
throw new UnsupportedOperationException();
}
public Component getChild(int i) {
throw new UnsupportedOperationException();
}
public void operation() {
}
}
public class Leaf extends Component {
String description;
public Leaf(String description) {
this.description = description;
}
public void operation() {
System.out.println("this is Leaf " + description + " operation.");
}
}
public class Composite extends Component{
List<component> components;
String description;
public Composite(String description) {
components = new ArrayList<>();
this.description = description;
}
public void add(Component component) {
components.add(component);
}
public void remove(Component component) {
components.remove(component);
}
public Component getChild(int i) {
return components.get(i);
}
public void operation() {
System.out.println("this is Composite " + description + " operation.");
}
}
/<component>/<code>

十二、狀態模式

定義:允許對象在內部狀態改變時改變它的行為,對象看起來好像修改了它的類。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface State {
public void handle();
}
public class OpenState implements State {
@Override
public void handle() {
System.out.println("It's opening!");
}

}
public class CloseState implements State {
@Override
public void handle() {
System.out.println("It's closed!");
}
}
public class Context {
private State openState;
private State closeState;
public Context() {
openState = new OpenState();
closeState = new CloseState();
}
public void open() {
openState.handle();
}
public void close() {
closeState.handle();
}
}
/<code>

十三、代理模式

定義:為另一個對象提供一個替身或佔位符以控制對這個對象的訪問。

作用:使用代理模式創建代表(representative)對象,讓代表對象控制某對象的訪問,被代理的對象可以是遠程的對象、創建開銷大的對象或需要安全控制的對象。

類圖:

來自阿里Java架構師的十三份設計模式筆記

源代碼:

<code>public interface Subject {
public void request();
}
class RealSubject implements Subject {
@Override
public void request() {
System.out.println("this is request in RealSubject.");
}
}
public class Proxy implements Subject {
Subject subject;
public Proxy() {
subject = new RealSubject();
}
@Override
public void request() {
subject.request();
}
}/<code>

寫在最後:

  • 針對於Java程序員,筆者最近整理了一些面試真題,思維導圖,程序人生等PDF學習資料;
  • 關注私信我"86",即可獲取!
  • 希望讀到這的您能點個小贊和關注下我,以後還會更新技術乾貨,謝謝您的支持!
來自阿里Java架構師的十三份設計模式筆記


分享到:


相關文章: