首页 > 其他分享 >四:轻松学设计模式:创建型、结构型、行为型概览

四:轻松学设计模式:创建型、结构型、行为型概览

时间:2023-04-30 14:10:09浏览次数:40  
标签:play String void 概览 public Child 设计模式 class 结构型

在软件开发的世界中,有一个众所周知的词汇——设计模式。设计模式是一种解决特定问题的优雅方案,代码让人看起来就有种自然的感觉。现在,我们就来轻松、幽默地了解一下这些神秘的设计模式吧!

创建型(Creational):生孩子还是领养?这里有五种方法!

1、单例模式(Singleton):只要一个宝贝!

想象一下,你的家里只能有一台电视机。这台电视机就像单例模式中的唯一实例。Java代码示例:

public class Television {
    private static Television instance;

    private Television() {
    }

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

2、工厂方法模式(Factory Method):专业的孩子制造工厂!

每个孩子都是独一无二的,工厂方法模式就像一个专业的孩子制造工厂,可以根据需求生产出不同类型的孩子。Java代码示例:

public interface Child {
    void play();
}

public class NaughtyChild implements Child {
    public void play() {
        System.out.println("I'm a naughty child!");
    }
}

public class QuietChild implements Child {
    public void play() {
        System.out.println("I'm a quiet child.");
    }
}

public abstract class ChildFactory {
    public abstract Child createChild();
}

3、抽象工厂模式(Abstract Factory):万能孩子制造厂!

抽象工厂模式就像一个万能孩子制造厂,不仅可以生产孩子,还能生产他们的玩具、衣服等。Java代码示例:

public interface Toy {
    void playWith();
}

public class CarToy implements Toy {
    public void playWith() {
        System.out.println("Vroom, vroom!");
    }
}

public class DollToy implements Toy {
    public void playWith() {
        System.out.println("Let's have a tea party!");
    }
}

public abstract class AbstractChildFactory {
    public abstract Child createChild();
    public abstract Toy createToy();
}

4、建造者模式(Builder):DIY你的孩子!

建造者模式就像用积木搭建玩具,你可以自由搭配各种属性,组成不同的孩子。Java代码示例:

public class ChildBuilder {
    private String name;
    private int age;
    private String hobby;

    public ChildBuilder setName(String name) {
        this.name = name;
        return this;
    }

    public ChildBuilder setAge(int age) {
        this.age = age;
        return this;
    }

    public ChildBuilder setHobby(String hobby) {
        this.hobby = hobby;
        return this;
    }

    public Child build() {
        return new Child(name, age, hobby);
    }
}

5、原型模式(Prototype):克隆孩子,简单快捷!

想要快速复制一个孩子?原型模式就像克隆技术,让你轻松复制孩子。Java代码示例:

public class Child implements Cloneable {
    private String name;

    public Child(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

结构型(Structural):孩子们的组织秘籍!

1、适配器模式(Adapter):兼容新老玩具!

适配器模式就像一个万能插头,让新旧玩具可以共用。Java代码示例:

public interface OldToy {
    void oldPlay();
}

public interface NewToy {
    void newPlay();
}

public class ToyAdapter implements NewToy {
    private OldToy oldToy;

    public ToyAdapter(OldToy oldToy) {
        this.oldToy = oldToy;
    }

    public void newPlay() {
        oldToy.oldPlay();
    }
}

2、桥接模式(Bridge):孩子与玩具的多样组合!

桥接模式就像拼图游戏,孩子和玩具可以任意组合。Java代码示例:

public interface Child {
    void play(Toy toy);
}

public interface Toy {
    void playWith();
}

public class Boy implements Child {
    public void play(Toy toy) {
        System.out.println("I'm a boy, and I'm playing with:");
        toy.playWith();
    }
}

public class Girl implements Child {
    public void play(Toy toy) {
        System.out.println("I'm a girl, and I'm playing with:");
        toy.playWith();
    }
}

3、组合模式(Composite):组织孩子们的团队!

组合模式就像树形结构,可以轻松地组织孩子们的团队。Java代码示例:

public abstract class ChildComponent {
    public void add(ChildComponent component) {
        throw new UnsupportedOperationException();
    }

    public void remove(ChildComponent component) {
        throw new UnsupportedOperationException();
    }

    public ChildComponent getChild(int index) {
        throw new UnsupportedOperationException();
    }

    public void play() {
        throw new UnsupportedOperationException();
    }
}

public class ChildGroup extends ChildComponent {
    private List<ChildComponent> components = new ArrayList<>();

    @Override
    public void add(ChildComponent component) {
        components.add(component);
    }

    @Override
    public void remove(ChildComponent component) {
        components.remove(component);
    }

    @Override
    public ChildComponent getChild(int index) {
        return components.get(index);
    }

    @Override
    public void play() {
        for (ChildComponent component : components) {
            component.play();
        }
    }
}

行为型(Behavioral):孩子们的行为规范!

1、观察者模式(Observer):妈妈总是知道!

观察者模式就像是妈妈总是知道孩子们在做什么。当孩子们的行为发生变化时,妈妈会立即得知。Java代码示例:

public interface Observer {
    void update(String message);
}

public interface Subject {
    void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

public class Child implements Subject {
    private List<Observer> observers;
    private String activity;

    public Child() {
        observers = new ArrayList<>();
    }

    public void setActivity(String activity) {
        this.activity = activity;
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(activity);
        }
    }
}

public class Mom implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Mom knows that the child is: " + message);
    }
}

2、策略模式(Strategy):适应不同的环境!

策略模式就像孩子们会根据不同的环境选择不同的玩法。Java代码示例:

public interface PlayStrategy {
    void play();
}

public class IndoorPlayStrategy implements PlayStrategy {
    public void play() {
        System.out.println("Playing indoors!");
    }
}

public class OutdoorPlayStrategy implements PlayStrategy {
    public void play() {
        System.out.println("Playing outdoors!");
    }
}

public class Child {
    private PlayStrategy playStrategy;

    public void setPlayStrategy(PlayStrategy playStrategy) {
        this.playStrategy = playStrategy;
    }

    public void play() {
        playStrategy.play();
    }
}

3、责任链模式(Chain of Responsibility):家庭责任制!

责任链模式就像家庭责任制,孩子们可以按照家庭规矩来处理问题。Java代码示例:

public abstract class Handler {
    protected Handler nextHandler;

    public void setNextHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public abstract void handleRequest(String request);
}

public class Father extends Handler {
    @Override
    public void handleRequest(String request) {
        if ("homework".equals(request)) {
            System.out.println("Father: I'll help with the homework.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

public class Mother extends Handler {
    @Override
    public void handleRequest(String request) {
        if ("housework".equals(request)) {
            System.out.println("Mother: I'll help with the housework.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

以上就是创建型、结构型、行为型设计模式的概览,希望通过这些生动、幽默的例子能让你对设计模式有更深入的了解。设计模式的运用能让你的代码更加优雅、易读,让软件开发变得更加轻松愉快!

标签:play,String,void,概览,public,Child,设计模式,class,结构型
From: https://blog.51cto.com/u_13616584/6237835

相关文章

  • 五:设计模式哲学:六大原则
    设计模式是软件开发中的经典解决方案,指导我们如何设计更优雅、灵活和可维护的代码。为了理解设计模式的核心思想,让我们从这六大原则出发,看看它们如何应用于日常编程中。在这篇文章中,我将为你揭示这些原则的精髓,并通过幽默、有趣的例子和Java代码来展示它们的应用。1、单一职责原则......
  • 【模板方法设计模式详解】C/Java/JS/Go/Python/TS不同语言实现
    简介模板方法模式(TemplateMethodPattern)也叫模板模式,是一种行为型模式。它定义了一个抽象公开类,包含基本的算法骨架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变算法的结构,只是重定义该算法的某些特定步骤。不同的子类以不同的方式实现这些抽象方法,从而对剩余的逻辑有......
  • JS 设计模式
    单例模式一个类只有一个实例,并提供一个访问它的全局访问点。1classLoginForm{2constructor(){3this.state='hide'4}5show(){6if(this.state==='show'){7alert('已经显示')8return9......
  • Java设计模式-单例模式
    一、前言单例模式是一种设计模式,它确保一个类只能创建一个实例,并提供一种全局访问这个实例的方式。在Java中,单例模式可以通过多种方式来实现,其中最常见的是使用私有构造函数和静态方法实现二、基本语法在Java中,实现单例模式的方式有多种,其中最常见的实现方式包括以下几种:1、......
  • 设计模式
    第一章软件架构设计原则1.1开闭原则开闭原则的核心思想就是面向抽象编程开闭原则是面向对象编程中的一个设计原则,也被称为OCP原则。它的定义为:软件中的对象(类、模块、函数等)应该对扩展开放,对修改关闭。换句话说,一个软件实体应该通过扩展来实现变化,而不是通过修改已有的代码......
  • 【策略设计模式详解】C/Java/JS/Go/Python/TS不同语言实现
    简介策略模式(StrategyPattern)属于行为型设计模式。将每一个算法封装到具有共同接口的独立类中,根据需要来绑定策略,使得具体实现和策略解耦。当你想使用对象中各种不同的算法变体,使用if...else所带来的复杂和难以维护,可使用策略模式。或者当有许多相同类,它们仅在执行某些行为时......
  • 设计模式-工厂篇(1)
    意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。FactoryMethod 使一个类的实例化延迟到其子类。适用性:当一个类不知道它所必须创建的对象的类的时候。当一个类希望由它的子类来指定它所创建的对象的时候。当类将创建对象的职责委托给多个帮助子类中的某一个,并且......
  • python的设计模式
    设计模式目录设计模式一、什么是设计模式二、python实现设计模式创建型模式1.单例模式2.工厂模式一、什么是设计模式软件工程中,设计模式是指软件设计问题的推荐方案。设计模式一般是描述如何组织代码和使用最佳实践来解决常见的设计问题。需要记住一点:设计模式是高层次的方案,并......
  • Java设计模式-抽象工厂模式
    简介设计模式是软件设计中的一种常见方法,通过定义一系列通用的解决方案,来解决常见的软件设计问题。其中,抽象工厂模式是一种非常常见的设计模式,它可以帮助我们创建一组相关的对象,而不需要指定具体的实现方式。抽象工厂模式是一种创建型设计模式,它提供了一种方式来创建一组相关的......
  • 设计模式小结
    简单工厂模式将具有相同属性事物用一个抽象基类,里面具有抽象方法来作为父类,然后其他子类通过继承来实现这个基类,通过重写实现基类里面的抽象方法创建一个工厂方法,通过父类变量来策略模式就是在简单工厂模式的基础上,将工厂方法改成策略对象,然后去调用该对象的重写基类的抽象方法单一......