Common design pattern code plus class diagram

Design Patterns

This article does not explain the design pattern, mainly based on sample code and class diagrams. It is suitable for those who have a certain foundation and want to review the design pattern. If you want to see the detailed explanation, please click here for the detailed design pattern . The class diagrams are all drawn by hand. It is recommended to be sure. Understand the class diagram.

Factory mode

// 顶层人类接口
public interface Person {
    
    
    void say();
}

// 中国人实现类
public class Chinese implements Person {
    
    
    public void say() {
    
    
        System.out.println("中国人说话:你好~");
    }
}

// 法国人实现类
public class French implements Person {
    
    
    public void say() {
    
    
        System.out.println("法国人说话:bonjour~");
    }
}

// 美国人实现类
public class American implements Person {
    
    
    public void say() {
    
    
        System.out.println("美国人说话:Hello~");
    }
}

// 人类工厂
public class PersonFactory {
    
    
    public static Person getPerson(String person) {
    
    
        if (person == null)
            return null;
        if (person.equalsIgnoreCase("CHINESE"))
            return new Chinese();
        if (person.equalsIgnoreCase("AMERICAN"))
            return new American();
        if (person.equalsIgnoreCase("FRENCH"))
            return new French();
        return null;
    }
}

// 测试工厂模式
public class FactoryTest {
    
    

    public static void main(String[] args) {
    
    
        Chinese chinese = (Chinese) PersonFactory.getPerson("chinese");
        chinese.say();

        French french = (French) PersonFactory.getPerson("french");
        french.say();

        American american = (American) PersonFactory.getPerson("american");
        american.say();
    }
}

Results of the

中国人说话:你好~
法国人说话:bonjour~
美国人说话:Hello~

UML class diagram
Insert picture description here

Abstract factory pattern

// 顶层人类接口
public interface Person {
    
    
    void say();
}

// 中国人实现类
public class Chinese implements Person {
    
    
    public void say() {
    
    
        System.out.println("中国人说话:你好~");
    }
}

// 法国人实现类
public class French implements Person {
    
    
    public void say() {
    
    
        System.out.println("法国人说话:bonjour~");
    }
}

// 美国人实现类
public class American implements Person {
    
    
    public void say() {
    
    
        System.out.println("美国人说话:Hello~");
    }
}

// 顶层工作接口
public interface Job {
    
    
    void work();
}

// 医生实现类
public class Doctor implements Job {
    
    
    public void work() {
    
    
        System.out.println("医生要治病救人");
    }
}

// 司机实现类
public class Driver implements Job {
    
    

    public void work() {
    
    
        System.out.println("司机要拉载乘客");
    }
}

// 老师实现类
public class Teacher implements Job {
    
    
    public void work() {
    
    
        System.out.println("老师要教育孩子");
    }
}

// 顶层抽象工厂接口
public interface AbstractFactory {
    
    
    Person getPerson(String person);
    Job getJob(String job);
}

// 人类工厂实现类
public class PersonFactory implements AbstractFactory{
    
    
    public Person getPerson(String person) {
    
    
        if (person == null)
            return null;
        if (person.equalsIgnoreCase("CHINESE"))
            return new Chinese();
        if (person.equalsIgnoreCase("AMERICAN"))
            return new American();
        if (person.equalsIgnoreCase("FRENCH"))
            return new French();
        return null;
    }

    public Job getJob(String job) {
    
    
        return null;
    }
}

// 工作工厂实现类
public class JobFactory implements AbstractFactory{
    
    
    public Person getPerson(String person) {
    
    
        return null;
    }

    public Job getJob(String job) {
    
    
        if (job == null)
            return null;
        if (job.equalsIgnoreCase("DOCTOR"))
            return new Doctor();
        if (job.equalsIgnoreCase("TEACHER"))
            return new Teacher();
        if (job.equalsIgnoreCase("DRIVER"))
            return new Driver();
        return null;
    }
}

// 测试抽象工厂模式
public class AbstractFactoryTest {
    
    
    public static void main(String[] args) {
    
    
        AbstractFactory personFactory = new PersonFactory();
        Chinese chinese = (Chinese) personFactory.getPerson("chinese");
        chinese.say();

        AbstractFactory jobFactory = new JobFactory();
        Doctor doctor = (Doctor) jobFactory.getJob("doctor");
        doctor.work();
    }
}

Results of the

中国人说话:你好~
医生要治病救人

UML class diagram
Insert picture description here

Singleton mode

  • The singleton mode ensures that there is only one object of this class in the system memory, which saves system resources. For some objects that need to be created and destroyed frequently, using the singleton mode can improve system performance
  • When you want to instantiate a singleton class, you must remember to use the corresponding method of obtaining the object instead of using new
  • Scenarios used in singleton mode: objects that need to be created and destroyed frequently, time-consuming or resource-consuming object creation (ie: heavyweight objects), but frequently used objects, tool objects, frequent Objects that access databases or files (such as data sources, session factories, etc.)
// 饿汉式单例(没有懒加载,推荐单线程使用)
public class SingletonHungry {
    
    
    private static SingletonHungry instance = new SingletonHungry();

    private SingletonHungry() {
    
    }

    public static SingletonHungry getInstance() {
    
    
        return instance;
    }
}

// 懒汉式单例(懒加载,线程不安全)
public class SingletonLazy {
    
    
    private static SingletonLazy instance;

    private SingletonLazy() {
    
    }

    public static SingletonLazy getInstance() {
    
    
        if (instance == null)
            instance = new SingletonLazy();
        return instance;
    }
}

//双重检查(线程安全,效率高)
public class SingletonDoubleCheck {
    
    
    private static volatile SingletonDoubleCheck instance;

    private SingletonDoubleCheck() {
    
    }

    public static SingletonDoubleCheck getInstance() {
    
    
        if (instance == null) {
    
    
            synchronized (SingletonDoubleCheck.class) {
    
    
                if (instance == null)
                    instance = new SingletonDoubleCheck();
            }
        }
        return instance;
    }
}

Results of the

测试饿汉单例:true
测试懒汉单例:true
测试双重检测单例:true

UML class diagram
Insert picture description here

Agency model

// 顶层找对象的接口(代理者和被代理都要同时实现该接口)
public interface FindLover {
    
    
    void blindDate();
}

// 程序员实现找对象接口(被代理者)
public class Programmer implements FindLover{
    
    
    public void blindDate() {
    
    
        System.out.println("卑微程序员相亲找对象");
    }
}

// 婚介所实现找对象接口(代理者)
public class DatingService implements FindLover{
    
    
    private Programmer programmer;

    public DatingService(Programmer programmer) {
    
    
        this.programmer = programmer;
    }

    public void blindDate() {
    
    
        beforeBlindDate();
        this.programmer.blindDate();
        afterBlindDate();
    }

    public void beforeBlindDate() {
    
    
        System.out.println("不敢迈出第一步,还是找婚介所帮忙吧");
    }

    public void afterBlindDate() {
    
    
        System.out.println("我一个35的程序员居然还能找到对象,我何德何能...");
    }
}

// 测试代理模式
public class ProxyTest {
    
    
    public static void main(String[] args) {
    
    
        Programmer you = new Programmer();
        FindLover datingService = new DatingService(you);
        datingService.blindDate();
    }
}

Results of the

不敢迈出第一步,还是找婚介所帮忙吧
卑微程序员相亲找对象
我一个35的程序员居然还能找到对象,我何德何能...

UML class diagram
Insert picture description here

Observer mode

// 程序员(被观察者)
public class Programmer {
    
    
    private List<Observer> observers = new ArrayList<Observer>();
    private boolean hasGirlFirend;

    public boolean isHasGirlFirend() {
    
    
        return hasGirlFirend;
    }

    public void setHasGirlFirend(boolean hasGirlFirend) {
    
    
        this.hasGirlFirend = hasGirlFirend;
        if (hasGirlFirend == true)
            notifyAllObservers();
    }

    public void attach(Observer observer) {
    
    
        observers.add(observer);
    }

    public void notifyAllObservers() {
    
    
        for (Observer observer : observers) {
    
    
            observer.knowMsg();
        }
    }
}

// 观察者抽象类
public abstract class Observer {
    
    
    protected Programmer programmer;
    abstract void knowMsg();
}

// 朋友 1 作为观察者
public class Friend1 extends Observer{
    
    

    public Friend1(Programmer programmer) {
    
    
        this.programmer = programmer;
        this.programmer.attach(this);
    }

    void knowMsg() {
    
    
        System.out.println("说好的一起代码到终老,你怎么能这样~");
    }
}

// 朋友 2 作为观察者
public class Friend2 extends Observer{
    
    

    public Friend2(Programmer programmer) {
    
    
        this.programmer = programmer;
        this.programmer.attach(this);
    }

    void knowMsg() {
    
    
        System.out.println("你再也不是爸爸的好儿子了,耗子为汁~");
    }
}

// 测试观察者模式
public class TestObserver {
    
    
    public static void main(String[] args) {
    
    
        Programmer you = new Programmer();
        // 将两个朋友添加到观察队列里
        new Friend1(you);
        new Friend2(you);

        // 程序员找到对象会通知所有朋友
        you.setHasGirlFirend(true);
    }
}

Results of the

说好的一起代码到终老,你怎么能这样~
你再也不是爸爸的好儿子了,耗子为汁~

UML class diagram
Insert picture description here

Strategy mode

// 策略接口
public interface Strategy {
    
    
    void doOperation();
}

// 策略实现类 1
public class LowKey implements Strategy{
    
    
    public void doOperation() {
    
    
        System.out.println("刚入职要低调做事~");
    }
}

// 策略实现类 2
public class WorkCrazy implements Strategy{
    
    
    public void doOperation() {
    
    
        System.out.println("入职之后要发奋工作~");
    }
}

// 策略实现类 3
public class DeleteData implements Strategy{
    
    
    public void doOperation() {
    
    
        System.out.println("压力太大,删库跑路~");
    }
}

// 策略启动类
public class Context {
    
    
    private Strategy strategy;

    public Context(Strategy strategy) {
    
    
        this.strategy = strategy;
    }

    public void doOperation() {
    
    
        this.strategy.doOperation();
    }
}

// 测试策略模式
public class StrategyTest {
    
    
    public static void main(String[] args) {
    
    
        Context context = new Context(new LowKey());
        // 执行第一个策略
        context.doOperation();

        // 执行第二个策略
        context = new Context(new WorkCrazy());
        context.doOperation();

        // 执行第三个策略
        context = new Context(new DeleteData());
        context.doOperation();
    }
}

Results of the

刚入职要低调做事~
入职之后要发奋工作~
压力太大,删库跑路~

UML class diagram
Insert picture description here


updating…

Guess you like

Origin blog.csdn.net/qq_42647711/article/details/109841509