Design patterns will eventually be incorporated into any language.

What are design patterns

From “The Myth of the Man-Month” to “Cathedral and Bazaar”, many well-known works in the industry are “low code, high culture”; The various code culture movements can be seen as Sunday theater of the God Making Movement. In addition to teaching people how to code, many gurus like to try to unify the relationship between people and code by cultural means, whether philosophical or artistic. The process of cross-boundary thinking is usually quite obscure. Terms such as “object orientation” and “design pattern”, which are familiar to us now, were developed by the industry’s top leaders in the past decades, and then gradually settled down into standards through continuous practice.

What are design patterns?

Design patterns are a standard that describes how problems can be solved using object-oriented programming languages.

The term design pattern, which originated in the architectural work The Language of Architectural Patterns, has been popularized in software by a group known as the Gang of Four (GoF). Both design patterns in architecture and software have the same thing in that they both want to solve the relationship between “people” and “things” and form a set of specific methodologies. For example, people who have a stove can keep fire for a long time, and the use of nouns to define obscure abstractions as standards helps to spread ideas. As long as design patterns are generally accepted and understood, the implementation of code can be communicated unimpeded. Of course, the reality is rich, and the big premise for smooth communication is that people need to use object-oriented programming languages to collaborate on programming.

Why object oriented

The construction of large-scale software is not only object oriented, but also corresponding to object oriented programming methods such as structure and formalization. Either one has its advantages and disadvantages. In the face of increasingly complex software, the focus of attention has gradually shifted to software reusability. With the advantages of classification, encapsulation and other natural laws in line with people’s cognition, object-oriented has been rapidly developed, and finally opened up the upstream and downstream work of demand analysis, program design to programming language development, and won the favor of the industry.

Object oriented function as nodes, combined into function grid, nodes through message communication and do the corresponding response. In this way, the development of programming does not need to face the input and output of the way of thinking about data flow, only need to maintain the internal state of each object according to the instructions, the node corresponding code fragments can be reused.

Function reuse has been a huge improvement over subroutine reuse. Class reuse is more abstract than function reuse because it preserves a collection of functions and states; Design patterns, on the other hand, are more abstract than class reuse: rather than simply reusing a class directly, design patterns reuse an entire “functional grid”, copying, solidifying, naming and standardizing all nodes and communication mechanisms associated with a particular problem solution. In fact, design pattern is a high-level form of code reuse when using object-oriented programming language. It is an inevitable outcome of the development of object-oriented. As long as you’re writing code, you’re going to run into reusability issues, and the Gang of Four have an object-oriented bias, so “design pattern” is just a generalization of what they’re teaching about code reusability in object-oriented programming. In other words, most of the time we’re talking about “design patterns” and “object-oriented design patterns.” This explains why it has to be object oriented.

When you filter out the object-oriented component of the design pattern, what is left?

console.log(DesignPatterns.filter(removeOO))
Copy the code

The nature of design patterns

We first delete directly above about design patterns, the definition of the words “object-oriented”, to see what he left: design patterns is a kind of standard, it describes the use of object-oriented programming language, the way to solve the problem, is the use of object-oriented programming language code reusability advanced forms, is the way of object-oriented development inevitable product.

A design pattern is a standard that describes a specific way of solving problems in programming. It is an advanced form of code reuse and an inevitable outcome of the development of code reuse.

What is the nature of design patterns? It goes without saying that it is just an abstraction for the reuse of related code.

When it comes to code reuse, it’s all about code organization. From function reuse, to the use of design patterns, to the use of libraries, frameworks, the main difference between the three methods of code reuse is the granularity of the code organization.

Function reuse is relatively easy, you can write a function called Add to Add two numbers, then Copy&Paste to reuse elsewhere, or put the function in a file Utils. Js, reuse through the module mechanism. To understand how to use a function, you need to read comments before using it.

Libraries and frameworks are the most complex, as they are large pieces of code that organize a large number of functions and entities. When developing a new project, we seldom spend effort to develop our own framework. We usually build it directly from off-the-shelf wheels. Before using a library or framework, you must read the documentation carefully.

A design pattern is a combination of single or multiple functions (not functions but classes in Java) that can be used either by writing a pattern in a new project or by introducing existing modules in the community. To understand how to use a design pattern, you need to know in advance what the pattern defines and what the entity is as a communication mechanism.

As the simplest combination of entity and function, design pattern can be regarded as an upgraded version of function or a reduced version of framework. Remove the object-oriented aspects of the design pattern, and you’re left with functions.

Wait, “entity to entity communication mechanism” disappeared into thin air?

Don’t. But I want him gone. Starting with JavaScript, I’ll show you how to map the concept of design patterns to language characteristics. Linguistic features are a good thing! If you agree that abstraction has the same level of complexity as reuse, such as function reuse, library and framework, then I think language features are the foundation of abstraction. In addition to the language itself, the establishment of all abstractions depends on language features. By mapping design patterns to language features, we can break out of object orientation and rethink code reuse from a new, higher-level perspective.

Back to business, let’s start with JS.

Imitation design pattern

Programming languages are not panacea. Specific languages are suitable for solving specific problems with CSS. When it comes to JavaScript’s many language features, the benefits can be summed up in three words: “prototype”, “object”, and “function”. Master these content, you will be able to navigate in the JS world.

Traditional object-oriented languages encapsulate state with classes and expose methods for changing state. Take the Book Class in the following code: The Book Class retains a name state. You can use getPrintName to return the wrapped name or rename to rename the name.

class Book {
  constructor () {
    this.name = 'Design Mode with JS Magic Pot'
  }
  getPrintName () {
    return ' ' ' + this.name + ' ' '
  }
  rename (newName) {
    this.name = newName
  }
}
Copy the code

In earlier versions of JS, if you want to encapsulate variables, it’s not easy. Earlier versions of JS did not have block-level scope, so declared variables were applied throughout the code or function scope. In order to imitate the state encapsulation capability of classes, Douglas, a well-known preacher, invented a “module pattern” called module-pattern, which controls the access of variables through closures. The code is as follows:

const aBook = (() = > {
  var name = 'Design Mode with JS Magic Pot'
  function getPrintName () {
    return ' ' ' + name + ' ' '
  }
  function rename (newName) {
    name = newName
  }
  return {
    getPrintName,
    rename
  }
})()
Copy the code

The modular pattern seems like a complement to language proficiency. After the release of ES6 in 2015, JavaScript language features were enhanced and the once popular word module mode almost disappeared from the web. We are now free to use classes to encapsulate state without having to write IIFE which is lame for lack of semantics.

Let’s take a look at the common decorator pattern in object orientation.

Let’s say you’re maintaining an open source project that has some outdated API and you want to say “Hello, this API will be removed in the next release” when someone calls it. This code could be written like this:

// There is currently no support for using decorators for object attributes, so this is a piece of pseudo-code
const myAPI = {
  @deprecate('WARN: oldAPI is decrapted, please use oldAPI_v2')
  oldAPI(){}}Copy the code

If it weren’t for the decorator proposal, I bet you five bucks there wouldn’t be a lot of articles in the community talking about the decorator model. But if you’ve looked at regular code, you’ll have noticed that higher-order functions are actually implementations of decorators. Functions are first-class citizens in JS, and it is extremely easy to copy certain design patterns through function composition. For example, in the following code, a factory pattern is copied using the “local application” function:

const Partial = (fn, ... args) = > (. rest) = >fn(... args, ... rest)const Adder = (a, b) = > a + b

const add5 = Partial(Adder, 5)

add5(5) / / > > > 10
add5(10) / / > > > 15
Copy the code

I guess you want to growl, “That’s not how factory mode is written!” . Ha ha, don’t be so stubborn, be flexible. The design pattern we’re talking about here is the object oriented hangover, almost the essence of the design pattern, reuse. In other words, a Partial is a function factory, a generator that produces a function that still accepts an argument.

Am I using classes?

No.

Did you use a prototype?

No.

So what am I writing?

Function.

A function, a function! Functions are the firstclass. Functions are called “closures” and “callbacks”. You’ll need them sooner or later. If you can’t talk about design patterns without talking about language features, you can’t have a problem talking about functions.

The pro-function and far-class writing helps us digest many kinds of design patterns, and let’s look at the final one, the proxy pattern.

ES6 natively supports the proxy mode. Yes, the “Proxy” in Vue3. There are a lot of articles in the community about the Vue3 principle analysis, so I won’t go into Proxy here. Here is a small example of using Proxy to intercept object operations.

/* Use the Proxy object to disable access to attributes in the object starting with an underscore */
const proxy = new Proxy({}, {
  set(target, key, value) {
    invariant(key, 'set')
    target[key] = value
    return true}})function invariant(key, action) {
  if (key.startsWith('_')) {
    throw new Error(`Invalid Key`)
  }
}

proxy._prop = 'somevalue'
// Error: Invalid Key
Copy the code

What would the proxy mode look like without ES 6?

Will become a bunch of functions annotated with Proxy Patterns, will be absorbed into a Readme in a Github library, or will become a few new “Proxy Patterns in JS” blogs in the community… Harm, it doesn’t matter.

The ablation of design patterns

In general, design patterns serve one of three purposes: creating objects, combining objects, and dealing with object dependencies. The reuse represented by the object-oriented design pattern can only be used in an object-oriented context. By moving away from object orientation, you can open up the hierarchy of code reuse, down to language features, down to frameworks.

As the lowest level of abstraction, JS language features are inseparable from the increasingly new language specifications. The overlap between design patterns and language features summarized above can be summarized as follows:

  • If the language itself is weak, the level of reuse can be improved by abstracting language features at a higher level, such as functions (i.e. inventing a new design pattern).
  • As languages become more powerful, the concept of design patterns weakens;

Sounds a bit like “design patterns are a complement to inadequate language capabilities.” Are we about to embark on a programming language crusade? It reminds me of Graham’s naked worship of “powerful language” in Hackers and Painters:

If you want to solve a difficult problem, it’s not about whether the language you use is strong or not, it’s about several things at once: (a) using a strong language; (b) Write a real-world compiler for this puzzle; (c) Or… You’ve turned yourself into the human compiler of this puzzle.

Graham sees design patterns as a way to compromise language capabilities: “The more powerful the language is, the shorter the program will be.” Of course, even if a language were powerful enough to dispel the myth of object-oriented design, the debate about the expressivity of languages would continue. The good news, though, is that it would be a mistake to talk about languages in isolation, just as no one would expect to write a Web program in assembly.

We don’t need to pursue the perfection of the programming language expressive, expressive and complexity are often are related, as all the languages in the world of circle will be accompanied by the evolution of words, pronunciation for and tolerance of wrong grammar, but few people say (or dare say) “you see, the vernacular writings in classical style is unqualified”.

We can talk about design patterns without object orientation, because we’re talking about code reuse. Even if you solve problems in a functional, declarative language, there may be a particular paradigm to follow. Imagine a design pattern in CSS. Huh? Does CSS have design patterns? I thought so. The three language characteristics of specificity, inheritance, and cascade are the design patterns of CSS. The various code organization/naming schemes (such as OOCSS and Atomic CSS) built on top of these three basic features also count.

The only constant is code reuse. All we’re doing is abstracting out different levels of code reuse. The most important thing is not to remember the entities in a design pattern and how they communicate, but to understand the context in which the abstract volume represented by the design pattern fits.

The magic pot of language

In Welsh mythology, there is a magic cauldron which, after a year and a day of boiling in a specific formula, will extract three drops of the cure for any problem.

The popularity of JavaScript is growing, the front-end community is becoming more active, and the specification is becoming more innovative. ESNeeext has added a lot of new ingredients to the magic pot, which is a good thing (in fact, I fully expect it to fill the pot). New language features can bring more possibilities, so far, the new features are likely to increase semantics, enhance expression, reduce the burden of thinking if-one-word. Feel free to stuff the ingredients into the cauldron! Let us pray that the day will come soon!

This article ends with the magic pot story, which is quite an interesting legend.

In a hidden corner of Ireland lives Ceridwen, a wizard of wisdom and magic. She had extraordinary abilities, but she had to give birth to an ugly son. So the mother tried her best to impart wisdom to him to make up for his ugliness. She turned to all kinds of witchcraft and secret, finally, finally found inspiration in a secret magic book.

The book told Kaliduin the secret: she needed to use a large magic pot, filled with red mountain flowers, wheat, fire salt, fairy ears, standing roots and spirit dust, boil in a fire for a year and a day. The result is a pot of deadly poison, but the first three drops of the liquid are a wise elixir filled with the spirit of prophecy.

Soon, the work of cooking the magic pot was organized by Carrie Doon, a blind man whose name was unknown was assigned to stir the cauldron, and the young Bach was responsible for the fire beneath it.

The stars clucked and panned in the sky, and the sun and moon went round and round the Earth… The herbs in the pot become more powerful over time. Carrie Doon felt so satisfied with the bubbling cauldron that she lay down beside the warm pot and fell asleep.

That’s when the accident happened. The hot cauldron accidentally spilled some liquid on the young Bach’s fingers, which he sucked without thinking. Like the prophecy of the magic book, Bach was instantly wise. Instantly he knew the dance of fire and the voice of water, the dignity of the mountains and the murmur of the wind… He knows a thousand secrets, and… Carrie Doon is gonna kill him!

In a panic, Bach turned into a hare and fled, and Carrie Doon woke up and quickly turned into a hound to track the past. Bach becomes a dove in the sky, she becomes an eagle; He becomes a running deer, she becomes a Wolf on the prairie; He became a grain of wheat in a barn, and she became a pecking hen…

The two men may have been at each other’s throats until today.

To read more

  • 15 years later, the author of GoF Design Patterns will talk about design patterns
  • Why can’t you mess with the tree

I hope this article has been helpful to you, and you are welcome to criticize or point out your mistakes.

Want to see how this article was created? You can find the answer from my blog project ~ welcome Star & Follow~ also please come to my online blog, the layout is super Nice oh ~


  1. Not derogatory sense. ↩
  2. See article: Subroutine (function) archaeology ↩
  3. Try writing a game using CSS? Even if it works, the process can be incredibly frustrating. ↩
  4. This module pattern is not the traditional object-oriented module pattern, which is defined at www.jdon.com/52843. ↩
  5. Call it and cherish it, and you may never hear the term “first-class citizen” again. ↩
  6. You don’t need to use a sentence when you can use one word. ↩