Design-Pattern | java中二十三种设计模式讲解,配合demo实现

 by   thousmile Java Version: Current License: No License

kandi X-RAY | Design-Pattern Summary

kandi X-RAY | Design-Pattern Summary

Design-Pattern is a Java library. Design-Pattern has no bugs, it has no vulnerabilities and it has low support. However Design-Pattern build file is not available. You can download it from GitHub.

设计模式概述: 根据《设计模式-可重用的面相对象软件元素》 一书所诉 一共有23种设计模式,可以分为三大类. 创造模式: 这些设计模式提供了一种创建对象,而隐藏创建逻辑的方法 不是直接使用 new 关键字来实例化对象,这使程序在决定对于给定的用例, 需要创建哪些对象时,具有更大的灵活性。. 结构模式: 这些设计模式涉及类和对象组成。 继承概念用于组成接口并定义方法组合对象以获得新功能 可以理解为,cpu+主板+内存条+硬盘 组合起来就是一台电脑. J2EE模式: 这些设计模式特别涉及表示层。 这些模式由Sun Java Center标识。. ---------------------------------- 23种 设计模式具体名称 ----------------------------------------. 创造设计模式: 工厂模式 抽象工厂模式 单例模式 原型模式 Builder模式. 结构设计模式: 适配器(Adapter)模式 桥接(Bridge)模式 组合模式 装饰者(Decorator)模式 外观(Facade)模式 享元(Flyweight)模式 代理(Proxy)模式. 行为设计模式: 责任链模式 命令模式 解释器模式 迭代器模式 调解者(Mediator)模式 备忘录模式 观察者模式 状态模式 策略模式 模板模式 访问者模式.
Support
    Quality
      Security
        License
          Reuse

            kandi-support Support

              Design-Pattern has a low active ecosystem.
              It has 6 star(s) with 4 fork(s). There are no watchers for this library.
              OutlinedDot
              It had no major release in the last 6 months.
              Design-Pattern has no issues reported. There are no pull requests.
              It has a neutral sentiment in the developer community.
              The latest version of Design-Pattern is current.

            kandi-Quality Quality

              Design-Pattern has no bugs reported.

            kandi-Security Security

              Design-Pattern has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.

            kandi-License License

              Design-Pattern does not have a standard license declared.
              Check the repository for any license declaration and review the terms closely.
              OutlinedDot
              Without a license, all rights are reserved, and you cannot use the library in your applications.

            kandi-Reuse Reuse

              Design-Pattern releases are not available. You will need to build from source code and install.
              Design-Pattern has no build file. You will be need to create the build yourself to build the component from source.

            Top functions reviewed by kandi - BETA

            kandi has reviewed Design-Pattern and discovered the below as its top functions. This is intended to give you an instant insight into Design-Pattern implemented functionality, and help decide if they suit your requirements.
            • Main command
            • Adds the file
            • Displays a tree recursively
            • Demonstrates a test program
            • Starts the asynchronous play
            • Main entry point
            • Power supplier
            • Main entry point
            • Gets the factory factory
            • Test program
            • Get myFlyweight instance
            • Show the activity
            • Show the vehicle
            • Show the widget
            • Removes the file from this folder
            • The main method
            • Sets the date
            • Changes the age
            • Sulfill the subject
            • Main method
            • Power 2 V
            • Main entry point for testing
            • Invoke a method on the proxy
            • Main method
            • Get a color instance from a String
            • Main program
            Get all kandi verified functions for this library.

            Design-Pattern Key Features

            No Key Features are available at this moment for Design-Pattern.

            Design-Pattern Examples and Code Snippets

            Tutorial: Builder design pattern + Jackson
            mavendot img1Lines of Code : 62dot img1no licencesLicense : No License
            copy iconCopy
            public class Person {
                private final String name;
                private final Integer age;
             
                // getters
            }
            
            
            private Person(String name, Integer age) {
                this.name = name;
                this.age = age;
            }
             
            static class Builder {
                String name;
                Integer age;  
            Load the design pattern books .
            javadot img2Lines of Code : 3dot img2License : Non-SPDX
            copy iconCopy
            public List load() {
                return designPatternBooks;
              }  

            Community Discussions

            QUESTION

            How should a "Bridge" design pattern be implemented for more than two hierarchies?
            Asked 2021-Jun-10 at 00:51

            This explains the "Bridge" pattern I'm referring to: https://refactoring.guru/design-patterns/bridge

            Here's a scenario from the post above:

            Say you have a geometric Shape class with a pair of subclasses: Circle and Square. You want to extend this class hierarchy to incorporate colors, so you plan to create Red and Blue shape subclasses. However, since you already have two subclasses, you’ll need to create four class combinations such as BlueCircle and RedSquare.

            The problem this scenario presents:

            Adding new shape types and colors to the hierarchy will grow it exponentially. For example, to add a triangle shape you’d need to introduce two subclasses, one for each color. And after that, adding a new color would require creating three subclasses, one for each shape type. The further we go, the worse it becomes.

            To avoid this problem, we implement the Bridge pattern like so:

            Extract the color-related code into its own class with two subclasses: Red and Blue. The Shape class then gets a reference field pointing to one of the color objects. Now the shape can delegate any color-related work to the linked color object. That reference will act as a bridge between the Shape and Color classes. From now on, adding new colors won’t require changing the shape hierarchy, and vice versa.

            I understand the how and why of this implementation.

            But what if we need a third hierarchy, e.g. BorderStyle (where a border style can be Straight, Wavy, or ZigZag?)

            I guess we could implement a second Implementor class for BorderStyle and pass it into a Shape constructor like so:

            ...

            ANSWER

            Answered 2021-Jun-10 at 00:45

            Yes, this works. There's nothing wrong with adding two Bridge relationships to one abstraction (beyond the complexity of juggling three different hierarchies).

            Decorator would certainly not work for this purpose, because it maintains a single hierarchy, which is known to the client. The Implementor hierarchy in a Bridge (or hierarchies in this case) are unknown to the client.

            I would make a clarification to the linked article, where it says,

            You want to extend this [shape] class hierarchy to incorporate colors

            I think this oversimplifies the motivation for a Bridge. The Implementors are not just some attributes you choose to add to your Abstraction to enhance it. Your Abstraction requires an Implementor in order to function at all. The method implementations within subclasses of Abstraction generally do little except call methods of the Implementor.

            The Abstraction represents your high-level, business API, while the Implementor represents a lower-level, primitive API. They are both abstractions, but at different levels. I don't think this is conveyed adequately by shape & color examples because shape and color seem like abstractions at the same level. Both shape and color would be known to the clients, and neither one strictly depends on the other.

            So a Bridge is applied for more specific reasons than the given example, but you certainly can have two.

            Source https://stackoverflow.com/questions/67909547

            QUESTION

            CMake with ROS Package:Header files not detected
            Asked 2021-Jun-09 at 04:22

            I am trying to organise my code into a more OOP style with each class taking on its own header and cpp file. This is my tree in the package folder in the workspace

            ...

            ANSWER

            Answered 2021-Jun-09 at 02:37

            In essence you don't need to include either header into the other. This fixes the circular includes. In ROS_Topic_Thread.h, friend class Master_Thread; already forward declares Mater_Thread, so you don't need the Master_Thread.h header. In Master_Thread.h, you can also forward declare class ROS_Topic_Thread; before the declaration of the Master_Thread class, since you only use references to ROS_Topic_Thread in the transfer_to_master_buffer method.

            Source https://stackoverflow.com/questions/67884798

            QUESTION

            C++ Evil Getter Setter against Factory/Builder design pattern
            Asked 2021-May-14 at 17:49

            I'm trying to learn the design pattern norme (like refacturing guru), and i have some problem to understand how i could merge the idea of bad design with public getter/setter and factory/Builder that need "out of constructor" variable setter.

            for example with the answer of this article to article to Design pattern

            As you can understand, each object will need a lot of informations, and adding part should set the needed informations, but to be able to do it, it need accessor to my variable outside the constructor.

            Help me figure out what i'm missing.

            --- Edit To be more precise, Let's say i have 2 class : CombatObject <---- Spaceships And i have a factory that will create different type of spaceships (principally because i don't want to create more than 10 class just to change the stats of the objects)

            in this case, getter/setter are not a bad design (or are they?)

            ...

            ANSWER

            Answered 2021-May-14 at 17:49

            Ok i think the comments are right, the way i see the solution is the following :

            No Setter, the only way to interact with the object will be with function with a purpose. For exemple, modify HP, add a DoDamage function that will return false if the ship is destoyed and will internally modify the hp (and maybe the damage too, etc..)

            Getter can be public, but of course, only "const &"

            Clone method is a good idea for future development (prototype pattern)

            Source https://stackoverflow.com/questions/67537957

            QUESTION

            singleton is design-pattern or anti-pattern?
            Asked 2021-Apr-30 at 09:05

            Some programmers believe Singleton is an anti-pattern

            I believe singleton is a design-pattern, but some articles and programmers disagree.

            Why? with reason

            ...

            ANSWER

            Answered 2021-Apr-30 at 09:04

            As far as I know, the book AntiPatterns by Brown et al, 1998 may have been the first to popularise the term. It defines an anti-pattern like this:

            "An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences."

            I think that it's worthwhile to pay attention to the phrase decidedly negative consequences. Most solutions come with some disadvantages, but in order for a 'solution' to be an anti-pattern, the disadvantages must clearly outweigh any advantages produced.

            I usually look at it another way. If I can solve the problem in a different way that generates at least as many advantages, but fewer disadvantages, then the first 'solution' might be an anti-pattern.

            As described in the GoF book, the Singleton design pattern addresses a particular problem: Sometimes you want to ensure that only one instance of a class can exist.

            This can be appropriate for performance reasons. If the object holds a large amount of data, making sure that only one exists could improve performance.

            Even if the object doesn't hold a large amount of memory, you may want to make a small immutable object a Singleton if you otherwise expect that client code might instantiate millions of identical objects.

            Particularly when the Singleton object represents immutable data it's hard to argue that it has decidedly negative consequences. It's basically just a constant, like string.Empty. The Singleton pattern is a good solution to that kind of problem.

            On the other hand, many people use mutable Singletons as a replacement for techniques like Dependency Injection or partial function application. When used in this way, a Singleton becomes a global variable, which most people nowadays agree should be avoided.

            Since Singleton has valid uses, I don't think it can be called an anti-pattern. On the other hand, I'd consider a mutable Singleton a code smell bordering on anti-pattern.

            Source https://stackoverflow.com/questions/67330429

            QUESTION

            Is event sourcing an enhanced pattern of choreography-based SAGA pattern?
            Asked 2021-Apr-02 at 13:08

            These days I am researching the Microservice inter-service communication patterns. So during my research, I found that there are two patterns called SAGA and event sourcing. But I couldn't find a resource on the internet to learn the difference between the two patterns. I mean I know event sourcing will capture the history of the event with the aid of an event store. So as per my understandings, I feel that event sourcing is like an extended version of choreography-based SAGA pattern. So I need to clarify is my argument acceptable or not. I will attach sample diagrams of the two patterns which I found on the internet below. Please use those diagrams during any of your explanations.

            References

            ...

            ANSWER

            Answered 2021-Apr-02 at 13:08

            The two are compatible patterns that address different problems, Sagas handle workflow processes where as event sourcing addresses how state is stored. Sagas provide a mechanism for handling a multi-step process and rolling back should steps fail (like a workflow). Where as Event Sourcing is the process of encoding the state of an entity by recording all its past changes.

            Sagas

            Lets say we are booking a holiday, we need to book flights, a hotel and hire a car. each of these processes is handled by a different microservice.

            We could create a microservice named BookingSaga which would be responsible for keeping track of the state of each booking. When we make a booking the BookingSaga service would

            • book the hotel
            • book the flight
            • book the car

            these can reply in any order, but if any one fails the BookingSaga would then begin a rollback and cancel any that had already been booked.

            https://microservices.io/patterns/data/saga.html

            Event Sourcing

            Event sourcing keeps track of the state of some entity by recording the changes that have happened to it.

            • Object A Name changed to "dave"
            • Object A Age Changed to 3
            • Object A Named changed to "sue"

            So we can see that Object A has a name of "sue" and an Age of 3 at the end of all the events. https://microservices.io/patterns/data/event-sourcing.html

            Source https://stackoverflow.com/questions/66918637

            QUESTION

            Objects are not valid as a React child (found: object with keys {children})
            Asked 2021-Apr-02 at 00:23

            I have read an interesting article that suggests to use a custom usechildProps hook to directly write dynamic elements in the parent rather than sending props. The article is here: https://medium.com/the-guild/the-coolest-most-underrated-design-pattern-in-react-cd6210956203

            Basically, instead of writing:

            ...

            ANSWER

            Answered 2021-Apr-02 at 00:23

            As the error says, you are trying to use an object as a react component (childProp.title, and childProp.content). It seems you want to use their children as "content".

            Source https://stackoverflow.com/questions/66912076

            QUESTION

            What functionality does it makes sense to implement using Rust enums?
            Asked 2021-Mar-30 at 04:46

            I'm having problem understanding the usefulness of Rust enums after reading The Rust Programming Language.

            In section 17.3, Implementing an Object-Oriented Design Pattern, we have this paragraph:

            If we were to create an alternative implementation that didn’t use the state pattern, we might instead use match expressions in the methods on Post or even in the main code that checks the state of the post and changes behavior in those places. That would mean we would have to look in several places to understand all the implications of a post being in the published state! This would only increase the more states we added: each of those match expressions would need another arm.

            I agree completely. It would be very bad to use enums in this case because of the reasons outlined. Yet, using enums was my first thought of a more idiomatic implementation. Later in the same section, the book introduces the concept of encoding the state of the objects using types, via variable shadowing.

            It's my understanding that Rust enums can contain complex data structures, and different variants of the same enum can contain different types.

            What is a real life example of a design in which enums are the better option? I can only find fake or very simple examples in other sources.

            I understand that Rust uses enums for things like Result and Option, but those are very simple uses. I was thinking of some functionality with a more complex behavior.

            This turned out to be a somewhat open ended question, but I could not find a useful response after searching Google. I'm free to change this question to a more closed version if someone could be so kind as to help me rephrase it.

            ...

            ANSWER

            Answered 2021-Mar-30 at 04:46

            A fundamental trade-off between these choices in a broad sense has a name: "the expression problem". You should find plenty on Google under that name, both in general and in the context of Rust.

            In the context of the question, the "problem" is to write the code in such a way that both adding a new state and adding a new operation on states does not involve modifying existing implementations.

            When using a trait object, it is easy to add a state, but not an operation. To add a state, one defines a new type and implements the trait. To add an operation, naively, one adds a method to the trait but has to intrusively update the trait implementations for all states.

            When using an enum for state, it is easy to add a new operation, but not a new state. To add an operation, one defines a new function. To add a new state, naively, one must intrusively modify all the existing operations to handle the new state.

            If I explained this well enough, hopefully it should be clear that both will have a place. They are in a way dual to one another.

            With this lens, an enum would be a better fit when the operations on the enum are expected to change more than the alternatives. For example, suppose you were trying to represent an abstract syntax tree for C++, which changes every three years. The set of types of AST nodes may not change frequently relative to the set of operations you may want to perform on AST nodes.

            With that said, there are solutions to the more difficult options in both cases, but they remain somewhat more difficult. And what code must be modified may not be the primary concern.

            Source https://stackoverflow.com/questions/66861488

            QUESTION

            Laravel with() together Table or Variable Name
            Asked 2021-Mar-29 at 18:00

            I was reading a blog related Repository Pattern. I saw use of withBlogs method.

            ...

            ANSWER

            Answered 2021-Mar-29 at 16:04

            It is used for passing data into views. The with method returns an instance of the view object so that you can continue chaining methods before returning the view. All of the syntax below archives the same thing:

            Source https://stackoverflow.com/questions/66856536

            QUESTION

            Strategy design pattern Example?
            Asked 2021-Mar-23 at 07:03

            Following is stretagy design pattern example take from here. First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.

            ...

            ANSWER

            Answered 2021-Mar-23 at 07:03
            1. I want to ask what is use of strategy pattern here?

            The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)

            2. We can directly call pay() method from there?

            I don't know exactly you mean

            3. Why do we need interface , all which does is call a method?

            We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:

            Source https://stackoverflow.com/questions/66734340

            QUESTION

            design pattern for undoing after I have commited the changes
            Asked 2021-Mar-22 at 09:19

            We can undo an action using Command or Memento pattern.

            If we are using kafka then we can replay the stream in reverse order to go back to the previous state.

            For example, Google docs/sheet etc. also has version history.

            in case of pcpartpicker, it looks like the following:

            For being safe, I want to commit everything but want to go back to the previous state if needed.

            I know we can disable auto-commit and use Transaction Control Language (COMMIT, ROLLBACK, SAVEPOINT). But I am talking about undoing even after I have commited the change.

            How can I do That?

            ...

            ANSWER

            Answered 2021-Mar-22 at 09:19

            There isn't a real generic answer to this question. It all depends on the structure of your database, span of the transactions across entities, distributed transactions, how much time/transactions are allowed to pass before your can revert the change, etc.

            Memento like pattern

            Memento Pattern is one of the possible approaches, however it needs to be modified due to the nature of the relational databases as follows:

            1. You need to have transaction log table/list that will hold the information of the entities and attributes (tables and columns) that ware affected by the transaction with their primary key, the old and new values (values before the transaction had occurred, and values after the transaction) as well as datetimestamp. This is same with the command (memento) pattern.
            2. Next you need a mechanism to identify the non-explicit updates that ware triggered by the stored procedures in the database as a consequence of the transaction. This is important, since a change in a table can trigger changes in other tables which ware not explicitly captured by the command.
            3. Mechanism for rollback will need to determine if the transaction is eligible for roll-back by building a list of subsequent transactions on the same entities and determine if this transaction is eligible for roll-back, or some subsequent transaction would need to be rolled-back as well before this transaction can be rolled-back.
            4. In case of a roll-back is allowed after longer period of time, or a near-realtime consumption of the data, there should also be a list of transaction observers, processes that need to be informed that the transaction is no longer valid since they already read the new data and took a decision based on it. Example would be a process generating a cumulative report. When transaction is rolled-back, the rollback will invalidate the report, so the report needs to be generated again.

            For a short term roll-back, mainly used for distributed transactions, you can check the Microservices Saga Pattern, and use it as a starting point to build your solution.

            History tables

            Another approach is to keep incremental updates or also known as history tables. Where each update of the row will be an insert in the history table with new version. Similar to previous case, you need to decide how far back you can go in the history when you try to rollback the committed transaction.

            Regulation issues

            Finally, when you work with business data such as invoice, inventory, etc. you also need to check what are the regulations related with the cancelation of committed transactions. As example, in the accounting systems, it's not allowed to delete data, rather a new row with the compensation is added (ex. removing product from shipment list will not delete the product, but add a row with -quantity to cancel the effect of the original row and keep audit track of the change at the same time.

            Source https://stackoverflow.com/questions/66740216

            Community Discussions, Code Snippets contain sources that include Stack Exchange Network

            Vulnerabilities

            No vulnerabilities reported

            Install Design-Pattern

            You can download it from GitHub.
            You can use Design-Pattern like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the Design-Pattern component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

            Support

            For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
            Find more information at:

            Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

            Find more libraries
            CLONE
          • HTTPS

            https://github.com/thousmile/Design-Pattern.git

          • CLI

            gh repo clone thousmile/Design-Pattern

          • sshUrl

            git@github.com:thousmile/Design-Pattern.git

          • Stay Updated

            Subscribe to our newsletter for trending solutions and developer bootcamps

            Agree to Sign up and Terms & Conditions

            Share this Page

            share link

            Consider Popular Java Libraries

            CS-Notes

            by CyC2018

            JavaGuide

            by Snailclimb

            LeetCodeAnimation

            by MisterBooo

            spring-boot

            by spring-projects

            Try Top Libraries by thousmile

            spring-admin-vue

            by thousmileJava

            sqlite-demo

            by thousmileJava

            molly-multi-tenant

            by thousmileJava

            thread

            by thousmileJava

            mbp-demo

            by thousmileJava