<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rasamanikkam Premasajan on Medium]]></title>
        <description><![CDATA[Stories by Rasamanikkam Premasajan on Medium]]></description>
        <link>https://medium.com/@premasajan25?source=rss-adfeb08545f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zd3VHGgSB6_hEYa5</url>
            <title>Stories by Rasamanikkam Premasajan on Medium</title>
            <link>https://medium.com/@premasajan25?source=rss-adfeb08545f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:35:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@premasajan25/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is virtualization?]]></title>
            <link>https://medium.com/@premasajan25/what-is-virtualization-c3949090358b?source=rss-adfeb08545f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3949090358b</guid>
            <dc:creator><![CDATA[Rasamanikkam Premasajan]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 12:33:57 GMT</pubDate>
            <atom:updated>2023-10-11T12:33:57.296Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Virtualization is the creation of a virtual — rather than actual — version of something, such as an operating system (OS), a server, a storage device or network resources.</strong></p><p>Virtualization uses software that simulates hardware functionality to create a virtual system. This practice allows IT organizations to operate multiple operating systems, more than one virtual system and various applications on a single server. The benefits of virtualization include greater efficiencies and economies of scale.</p><p>OS virtualization is the use of software to allow a piece of hardware to run multiple operating system images at the same time. The technology got its start on mainframes decades ago, allowing administrators to avoid wasting expensive processing power.</p><h4><strong>How virtualization works</strong></h4><p>Virtualization describes a technology in which an application, guest OS or data storage is abstracted away from the true underlying hardware or software.</p><p>A key use of virtualization technology is server virtualization, which uses a software layer — called a hypervisor&lt;/a — to emulate the underlying hardware. This often includes the CPU’s memory, input/output (I/O) and network traffic.</p><p>Hypervisors take the physical resources and separate them so they can be utilized by the virtual environment. They can sit on top of an OS or they can be directly installed onto the hardware. The latter is how most enterprises virtualize their systems.</p><p>The Xen hypervisor is an open source software program that is responsible for managing the low-level interactions that occur between virtual machines (VMs) and the physical hardware. In other words, the Xen hypervisor enables the simultaneous creation, execution and management of various virtual machines in one physical environment.</p><p>With the help of the hypervisor, the guest OS, normally interacting with true hardware, is now doing so with a software emulation of that hardware; often, the guest OS has no idea it’s on virtualized hardware.</p><p>While the performance of this virtual system is not equal to the performance of the operating system running on true hardware, the concept of virtualization works because most guest operating systems and applications don’t need the full use of the underlying hardware.</p><p>This allows for greater flexibility, control and isolation by removing the dependency on a given hardware platform. While initially meant for server virtualization, the concept of virtualization has spread to applications, networks, data and desktops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKoh2zrDMakxgzL1Uz_gwg.jpeg" /></figure><h4><strong>The virtualization process follows the steps listed below:</strong></h4><ul><li>Hypervisors detach the physical resources from their physical environments.</li><li>Resources are taken and divided, as needed, from the physical environment to the various virtual environments.</li><li>System users work with and perform computations within the virtual environment.</li><li>Once the virtual environment is running, a user or program can send an instruction that requires extra resources form the physical environment. In response, the hypervisor relays the message to the physical system and stores the changes. This process will happen at an almost native speed.</li></ul><p>The virtual environment is often referred to as a guest machine or virtual machine. The VM acts like a single data file that can be transferred from one computer to another and opened in both; it is expected to perform the same way on every computer.</p><h3><strong>Types of virtualization</strong></h3><p>You probably know a little about virtualization if you have ever divided your hard drive into different partitions. A partition is the logical division of a hard disk drive to create, in effect, two separate hard drives.</p><p><em>There are six areas of IT where virtualization is making headway:</em></p><ol><li><strong>Network virtualization </strong>is a method of combining the available resources in a network by splitting up the available bandwidth into channels, each of which is independent from the others and can be assigned — or reassigned — to a particular server or device in real time. The idea is that virtualization disguises the true complexity of the network by separating it into manageable parts, much like your partitioned hard drive makes it easier to manage your files.</li><li><strong>Storage virtualization </strong>is the pooling of physical storage from multiple network storage devices into what appears to be a single storage device that is managed from a central console. Storage virtualization is commonly used in storage area networks.</li><li><strong>Server virtualization</strong> is the masking of server resources — including the number and identity of individual physical servers, processors and operating systems — from server users. The intention is to spare the user from having to understand and manage complicated details of server resources while increasing resource sharing and utilization and maintaining the capacity to expand later. The layer of software that enables this abstraction is often referred to as the hypervisor. The most common hypervisor — Type 1 — is designed to sit directly on bare metal and provide the ability to virtualize the hardware platform for use by the virtual machines. KVM virtualization is a Linux kernel-based virtualization hypervisor that provides Type 1 virtualization benefits like other hypervisors. KVM is licensed under open source. A Type 2 hypervisor requires a host operating system and is more often used for testing and labs</li><li><strong>Data virtualization </strong>is abstracting the traditional technical details of data and data management, such as location, performance or format, in favor of broader access and more resiliency tied to business needs.</li><li><strong>Desktop virtualization</strong> is virtualizing a workstation load rather than a server. This allows the user to access the desktop remotely, typically using a thin client at the desk. Since the workstation is essentially running in a data center server, access to it can be both more secure and portable. The operating system license does still need to be accounted for as well as the infrastructure.</li><li><strong>Application virtualization</strong> is abstracting the application layer away from the operating system. This way, the application can run in an encapsulated form without being depended upon on by the operating system underneath. This can allow a Windows application to run on Linux and vice versa, in addition to adding a level of isolation.</li></ol><p>Virtualization can be viewed as part of an overall trend in enterprise IT that includes autonomic computing, a scenario in which the IT environment will be able to manage itself based on perceived activity, and utility computing, in which computer processing power is seen as a utility that clients can pay for only as needed. The usual goal of virtualization is to centralize administrative tasks while improving scalability and workloads.</p><h3><strong>Advantages of virtualization</strong></h3><p><em>The advantages of utilizing a virtualized environment include the following:</em></p><p><strong>Lower costs.</strong> Virtualization reduces the amount of hardware servers necessary within a company and data center. This lowers the overall cost of buying and maintaining large amounts of hardware.</p><p><strong>Easier disaster recovery.</strong> Disaster recovery is very simple in a virtualized environment. Regular snapshots provide up-to-date data, allowing virtual machines to be feasibly backed up and recovered. Even in an emergency, a virtual machine can be migrated to a new location within minutes</p><p><strong>Easier testing.</strong> Testing is less complicated in a virtual environment. Even if a large mistake is made, the test does not need to stop and go back to the beginning. It can simply return to the previous snapshot and proceed with the test.</p><p><strong>Quicker backups. </strong>Backups can be taken of both the virtual server and the virtual machine. Automatic snapshots are taken throughout the day to guarantee that all data is up-to-date. Furthermore, the virtual machines can be easily migrated between each other and efficiently redeployed.</p><p><strong>Improved productivity</strong>. Fewer physical resources result in less time spent managing and maintaining the servers. Tasks that can take days or weeks in a physical environment can be done in minutes. This allows staff members to spend the majority of their time on more productive tasks, such as raising revenue and fostering business initiatives.</p><h3><strong>Benefits of virtualization</strong></h3><p>Virtualization provides companies with the benefit of maximizing their output. Additional benefit for both businesses and data centers include the following:</p><p><strong>Single-minded servers.</strong> Virtualization provides a cost-effective way to separate email, database and web servers, creating a more comprehensive and dependable system.</p><p><strong>Expedited deployment and redeployment. </strong>When a physical server crashes, the backup server may not always be ready or up to date. There also may not be an image or clone of the server available. If this is the case, then the redeployment process can be time-consuming and tedious. However, if the data center is virtualized, then the process is quick and fairly simple. Virtual backup tools can expedite the process to minutes.</p><p><strong>Reduced heat and improved energy savings.</strong> Companies that use a lot of hardware servers risk overheating their physical resources. The best way to prevent this from happening is to decrease the number of servers used for data management, and the best way to do this is through virtualization.</p><p><strong>Better for the environment.</strong> Companies and data centers that utilize copious amounts of hardware leave a large carbon footprint; they must take responsibility for the pollution they are generating. Virtualization can help reduce these effects by significantly decreasing the necessary amounts of cooling and power, thus helping clean the air and the atmosphere. As a result, companies and data centers that virtualize will improve their reputation while also enhancing the quality of their relationship with customers and the planet.</p><p><strong>Easier migration to the cloud.</strong> Virtualization brings companies closer to experiencing a completely cloud-based environment. Virtual machines may even be deployed from the data center in order to build a cloud-based infrastructure. The ability to embrace a cloud-based mindset with virtualization makes migrating to the cloud even easier.</p><p><strong>Lack of vendor dependency.</strong> Virtual machines are agnostic in hardware configuration. As a result, virtualizing hardware and software means that a company does not need to depend on a vendor for these physical resources.</p><p>………………………………………………………………………………………………….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3949090358b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Distributed Systems? Architecture Types, Key Components, and Examples]]></title>
            <link>https://medium.com/@premasajan25/what-are-distributed-systems-architecture-types-key-components-and-examples-3e709926f22d?source=rss-adfeb08545f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e709926f22d</guid>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Rasamanikkam Premasajan]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 05:50:11 GMT</pubDate>
            <atom:updated>2023-09-03T05:50:11.393Z</atom:updated>
            <content:encoded><![CDATA[<p>Distributed computing is defined as a system consisting of software components spread over different computers but running as a single entity. A distributed system can be an arrangement of different configurations, such as mainframes, computers, workstations, and minicomputers. This article gives in-depth insights into the working of distributed systems, the types of system architectures, and essential components with real-world examples.</p><h3>What Is Distributed Computing?</h3><p>Distributed computing is a system of software components spread over different computers but running as a single entity. A distributed system can be an arrangement of different configurations, such as mainframes, computers, workstations, and minicomputers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*93YWZqn4yTIC3pVP_n0LCQ.png" /></figure><h4>Distributed System</h4><p>Sharing resources such as hardware, software, and data is one of the principles of cloud computing. With different levels of openness to the software and concurrency, it’s easier to process data simultaneously through multiple processors. The more fault-tolerant an application is, the more quickly it can recover from a system failure.</p><p>Organizations have turned to distributed computing systems to handle data generation explosion and increased application performance needs. These distributed systems help businesses scale as data volume grows. This is especially true because the process of adding hardware to a distributed system is simpler than upgrading and replacing an entire centralized system made up of powerful servers.</p><p>Distributed systems consist of many nodes that work together toward a single goal. These systems function in two general ways, and both of them have the potential to make a huge difference in an organization.</p><ul><li>The first type is a cohesive system where the customer has each machine, and the results are routed from one source.</li><li>The second type allows each node to have an end-user with their own needs, and the distributed system facilitates sharing resources or communication.</li></ul><h4>Benefits of a multi-computer model</h4><ul><li>Improved scalability: Distributed computing clusters are a great way to scale your business. They use a ‘scale-out architecture,’ which makes adding new hardware easier as load increases.</li><li>Enhanced performance: This model uses ‘parallelism’ for the divide-and-conquer approach. In other words, all computers in the cluster simultaneously handle a subset of the overall task. Therefore, as the load increases, businesses can add more computers and optimize overall performance.</li><li>Cost-effectiveness: The cost-efficiency of a distributed system depends on its latency, response time, bandwidth, and throughput. Distributed systems work toward a common goal of delivering high performance by minimizing latency and enhancing response time and throughput. They achieve this goal by using low-cost commodity hardware to ensure zero data loss, making initial deployments and cluster expansions easy.</li></ul><h4>Architecture of Distributed Systems</h4><p>Cloud-based software, the backbone of distributed systems, is a complicated network of servers that anyone with an internet connection can access. In a distributed system, components and connectors arrange themselves in a way that eases communication. Components are modules with well-defined interfaces that can be replaced or reused. Similarly, connectors are communication links between modules that mediate coordination or cooperation among components.</p><p>A distributed system is broadly divided into two essential concepts — software architecture (further divided into layered architecture, object-based architecture, data-centered architecture, and event-based architecture) and system architecture (further divided into client-server architecture and peer-to-peer architecture).</p><p><strong>1. Software architecture</strong></p><p>Software architecture is the logical organization of software components and their interaction with other structures. It is at a lower level than system architecture and focuses entirely on components; e.g., the web front end of an ecommerce system is a component. The four main architectural styles of distributed systems in software components entail:</p><p><strong>i) Layered architecture</strong></p><p>Layered architecture provides a modular approach to software. By separating each component, it is more efficient. For example, the open systems interconnection (OSI) model uses a layered architecture for better results. It does this by contacting layers in sequence, which allows it to reach its goal. In some instances, the implementation of layered architecture is in cross-layer coordination. Under cross-layer, the interactions can skip any adjacent layer until it fulfills the request and provides better performance results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*gmAYT6VFxwaPSb6MfCNo5g.png" /></figure><h3>Layered Architecture</h3><p>Layered architecture is a type of software that separates components into units. A request goes from the top down, and the response goes from the bottom up. The advantage of layered architecture is that it keeps things orderly and modifies each layer independently without affecting the rest of the system.</p><p><strong>ii) Object-based architecture</strong></p><p>Object-based architecture centers around an arrangement of loosely coupled objects with no specific architecture like layers. Unlike layered architecture, object-based architecture doesn’t have to follow any steps in a sequence. Each component is an object, and all the objects can interact through an interface (or connector). Under object-based architecture, such interactions between components can happen through a direct method call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*cyqE9uGmOZIBDO4UZ1nHJw.png" /></figure><p>Object-based Architecture</p><p>At its core, communication between objects happens through method invocations, often called remote procedure calls (RPC). Popular RPC systems include Java RMI and Web Services and REST API Calls. The primary design consideration of these architectures is that they are less structured. Here, component equals object, and connector equals RPC or RMI.</p><p><strong>iii) Data-centered architecture</strong></p><p>Data-centered architecture works on a central data repository, either active or passive. Like most producer-consumer scenarios, the producer (business) produces items to the common data store, and the consumer (individual) can request data from it. Sometimes, this central repository can be just a simple database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*xcML5v0DVVBd4gShUDl3gw.png" /></figure><p><strong>Data-centered Architecture</strong></p><p>All communication between objects happens through a data storage system in a data-centered system. It supports its stores’ components with a persistent storage space such as an SQL database, and the system stores all the nodes in this data storage.</p><p><strong>iv) Event-based architecture</strong></p><p>In event-based architecture, the entire communication is through events. When an event occurs, the system gets the notification. This means that anyone who receives this event will also be notified and has access to information. Sometimes, these events are data, and at other times they are URLs to resources. As such, the receiver can process what information they receive and act accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*deaz3phqAUEGfK12BkMnGQ.png" /></figure><p>One significant advantage of event-based architecture is that the components are loosely coupled. Eventually, it means that it’s easy to add, remove, and modify them. To better understand this, think of publisher-subscriber systems, enterprise services buses, or akka.io. One advantage of event-based architecture is allowing heterogeneous components to communicate with the bus, regardless of their communication protocols.</p><h3>2. System architecture</h3><p>System-level architecture focuses on the entire system and the placement of components of a distributed system across multiple machines. The client-server architecture and peer-to-peer architecture are the two major system-level architectures that hold significance today. An example would be an ecommerce system that contains a service layer, a database, and a web front.</p><p><strong>i) Client-server architecture</strong></p><p>As the name suggests, client-server architecture consists of a client and a server. The server is where all the work processes are, while the client is where the user interacts with the service and other resources (remote server). The client can then request from the server, and the server will respond accordingly. Typically, only one server handles the remote side; however, using multiple servers ensures total safety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*2VcaOtpN6RFJ_cs4UbSDJw.png" /></figure><h3><strong>Client-server Architecture</strong></h3><p>Client-server architecture has one standard design feature: centralized security. Data such as usernames and passwords are stored in a secure database for any server user to have access to this information. This makes it more stable and secure than peer-to-peer. This stability comes from client-server architecture, where the security database can allow resource usage in a more meaningful way. The system is much more stable and secure, even though it isn’t as fast as a server. The disadvantages of a distributed system are its single point of failure and not being as scalable as a server.</p><p><strong>ii) Peer-to-peer (P2P) architecture</strong></p><p>A peer-to-peer network, also called a (P2P) network, works on the concept of no central control in a distributed system. A node can either act as a client or server at any given time once it joins the network. A node that requests something is called a client, and one that provides something is called a server. In general, each node is called a peer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7fqTdyISp7dxlxBi07xvbA.png" /></figure><h3>Peer-to-Peer Architecture</h3><p>If a new node wishes to provide services, it can do so in two ways. One way is to register with a centralized lookup server, which will then direct the node to the service provider. The other way is for the node to broadcast its service request to every other node in the network, and whichever node responds will provide the requested service.</p><p><strong>P2P networks of today have three separate sections:</strong></p><ul><li>Structured P2P: The nodes in structured P2P follow a predefined distributed data structure.</li><li>Unstructured P2P: The nodes in unstructured P2P randomly select their neighbors.</li><li>Hybrid P2P: In a hybrid P2P, some nodes have unique functions appointed to them in an orderly manner.</li></ul><h4>Key Components of a Distributed System</h4><p>The three basic components of a distributed system include primary system controller, system data store, and database. In a non-clustered environment, optional components consist of user interfaces and secondary controllers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*3paMHl39Ske6K4G2L8uEcg.png" /></figure><p><strong>1. Primary system controller</strong></p><p>The primary system controller is the only controller in a distributed system and keeps track of everything. It’s also responsible for controlling the dispatch and management of server requests throughout the system. The executive and mailbox services are installed automatically on the primary system controller. In a non-clustered environment, optional components consist of a user interface and secondary controllers.</p><p><strong>2. Secondary controller</strong></p><p>The secondary controller is a process controller or a communications controller. It’s responsible for regulating the flow of server processing requests and managing the system’s translation load. It also governs communication between the system and VANs or trading partners.</p><p><strong>3. User-interface client</strong></p><p>The user interface client is an additional element in the system that provides users with important system information. This is not a part of the clustered environment, and it does not operate on the same machines as the controller. It provides functions that are necessary to monitor and control the system.</p><p><strong>4. System datastore</strong></p><p>Each system has only one data store for all shared data. The data store is usually on the disk vault, whether clustered or not. For non-clustered systems, this can be on one machine or distributed across several devices, but all of these computers must have access to this datastore.</p><p><strong>5. Database</strong></p><p>In a distributed system, a relational database stores all data. Once the data store locates the data, it shares it among multiple users. Relational databases can be found in all data systems and allow multiple users to use the same information simultaneously.</p><h4>Examples of a Distributed System</h4><p>When processing power is scarce, or when a system encounters unpredictable changes, distributed systems are ideal, and they help balance the workload. Hence distributed systems have boundless use cases varying from electronic banking systems to multiplayer online games. Let’s check out more explicit instances of distributed systems:</p><p><strong>1. Networks</strong></p><p>The 1970s saw the invention of Ethernet and LAN (local area networks), which enabled computers to connect in the same area. Peer-to-peer networks developed, and e-mail and the internet continue to be the biggest examples of distributed systems.</p><p><strong>2. Telecommunication networks</strong></p><p>Telephone and cellular networks are other examples of peer-to-peer networks. Telephone networks started as an early example of distributed communication, and cellular networks are also a form of distributed communication systems. With the implementation of Voice over Internet (VoIP) communication systems, they grow more complex as distributed communication networks.</p><p><strong>3. Real-time systems</strong></p><p>Real-time systems are not limited to specific industries. These systems can be used and seen throughout the world in the airline, ride-sharing, logistics, financial trading, massively multiplayer online games (MMOGs), and ecommerce industries. The focus in such systems is on the correspondence and processing of information with the need to convey data promptly to a huge number of users who have an expressed interest in such data.</p><p><strong>4. Parallel processors</strong></p><p>Parallel computing splits specific tasks among multiple processors. This, in turn, creates pieces to put together and form an extensive computational task. Previously, parallel computing only focused on running software on multiple threads or processors accessing the same data and memory. As operating systems became more prevalent, they too fell into the category of parallel processing.</p><p><strong>5. Distributed database systems</strong></p><p>A distributed database is spread out across numerous servers or regions. Data can be replicated across several platforms. A distributed database system can be either homogeneous or heterogeneous in nature. A homogeneous distributed database uses the same database management system and data model across all systems.</p><p>Adding new nodes and locations makes it easier to control and scale performance. On the other hand, multiple data models and database management systems are possible with heterogeneous distributed databases. Gateways are used to translate data across nodes and are typically created due to the merger of two or more applications or systems.</p><p><strong>6. Distributed artificial intelligence</strong></p><p>Distributed artificial intelligence is one of the many approaches of artificial intelligence that is used for learning and entails complex learning algorithms, large-scale systems, and decision making. It requires a large set of computational data points located in various locations.</p><p><strong>A few real-world examples of distributed systems include:</strong></p><ul><li>Video-rendering systems</li><li>Scientific computing</li><li>Airline and hotel reservation</li><li>Cryptocurrency processors like Bitcoin</li><li>P2P file-sharing like BitTorrent</li><li>Multiplayer video games</li><li>E-learning applications</li><li>Distributed supply chains like Amazon</li></ul><h4>Takeaway</h4><p>Distributed systems are the most significant benefactor behind modern computing systems due to their capability of providing scalable and improved performance. Distributed systems are an essential component of wireless networks, cloud computing, and the internet. Since they can draw on the resources of other devices and processes, distributed systems offer some features that would be hard or even impossible to develop on a singular system and have become immensely reliable by combining the power of multiple machines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e709926f22d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software design patterns]]></title>
            <link>https://medium.com/@premasajan25/software-design-patterns-1bedd2835c29?source=rss-adfeb08545f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bedd2835c29</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <dc:creator><![CDATA[Rasamanikkam Premasajan]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 15:07:03 GMT</pubDate>
            <atom:updated>2023-08-25T07:47:56.674Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Design Patterns</strong></h3><p>In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.</p><h4>Some of the popular design patterns:</h4><p>Design Patterns | Set 1 (Introduction)</p><p>Design Patterns | Set 2 (Factory Method)</p><p>Observer Pattern | Set 1 (Introduction)</p><p>Observer Pattern | Set 2 (Implementation)</p><p>Singleton Design Pattern</p><ul><li>Singleton Class in Java</li><li>Singleton Design Pattern in Java</li><li>Singleton Design Practices with Examples</li><li>Prevent Singleton Patterns from Reflection, Serialization and Cloning</li></ul><p>Decorator Pattern | Set 1 (Background)</p><p>The Decorator Pattern | Set 2 (Introduction and Design)</p><p>Strategy Pattern | Set 1 (Introduction)</p><p>Strategy Pattern | Set 2 (Implementation)</p><p>Adapter Pattern</p><p>Command Pattern</p><p>Iterator Pattern</p><ul><li>Iterator Pattern of a Single Linked List</li></ul><p>Curiously recurring template pattern (CRTP)</p><p>Flyweight Design Pattern</p><p>Facade Design Pattern | Introduction</p><p>Proxy Design Pattern</p><p>Composite Design Pattern</p><p>Prototype Design Pattern</p><p>Abstract Factory Pattern</p><p>Bridge Design Pattern</p><p>Template Method Design Pattern</p><p>Builder Design Pattern</p><p>Chain of Responsibility Design Pattern</p><p>Unified Modeling Language (UML) | Class Diagrams</p><h4>Uses of Design Patterns</h4><p>Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.</p><p>Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn’t require specifics tied to a particular problem.</p><p>In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.</p><h3>Creational design patterns</h3><p>These design patterns are all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.</p><h3>Structural design patterns</h3><p>These design patterns are all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality.</p><h3>Behavioral design patterns</h3><p>These design patterns are all about Class’s objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects</p><h4>Targets the wrong problem</h4><p>The need for patterns results from using computer languages or techniques with insufficient abstraction ability. Under ideal factoring, a concept should not be copied, but merely referenced. But if something is referenced instead of copied, then there is no “pattern” to label and catalog. Paul Graham writes in the essay Revenge of the Nerds.</p><p>Peter Norvig provides a similar argument. He demonstrates that 16 out of the 23 patterns in the Design Patterns book (which is primarily focused on C++) are simplified or eliminated (via direct language support) in Lisp or Dylan.</p><h3>Abstract Factory Design Pattern</h3><h4>Intent</h4><ul><li>Provide an interface for creating families of related or dependent objects without specifying their concrete classes.</li><li>A hierarchy that encapsulates: many possible “platforms”, and the construction of a suite of “products”.</li><li>The new operator considered harmful.</li></ul><h4>Problem</h4><p>If an application is to be portable, it needs to encapsulate platform dependencies. These “platforms” might include: windowing system, operating system, database, etc. Too often, this encapsulation is not engineered in advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code.</p><h4>Discussion</h4><p>Provide a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The “factory” object has the responsibility for providing creation services for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for them.</p><p>This mechanism makes exchanging product families easy because the specific class of the factory object appears only once in the application — where it is instantiated. The application can wholesale replace the entire family of products simply by instantiating a different concrete instance of the abstract factory.</p><p>Because the service provided by the factory object is so pervasive, it is routinely implemented as a Singleton.</p><h4>Structure</h4><p>The Abstract Factory defines a Factory Method per product. Each Factory Method encapsulates the new operator and the concrete, platform-specific, product classes. Each “platform” is then modeled with a Factory derived class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*gd5MInftscXJcBSB" /></figure><h4>Example</h4><p>The purpose of the Abstract Factory is to provide an interface for creating families of related objects, without specifying concrete classes. This pattern is found in the sheet metal stamping equipment used in the manufacture of Japanese automobiles. The stamping equipment is an Abstract Factory which creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*TOEJq8yOfdWH_UT-" /></figure><h4>Implementation</h4><p>Let’s take an example, Suppose we want to build a global car factory. If it was a factory design pattern, then it was suitable for a single location. But for this pattern, we need multiple locations and some critical design changes.</p><p>We need car factories in each location like IndiaCarFactory, USACarFactory, and DefaultCarFactory. Now, our application should be smart enough to identify the location where it is being used, so we should be able to use the appropriate car factory without even knowing which car factory implementation will be used internally. This also saves us from someone calling the wrong factory for a particular location.</p><p>Here we need another layer of abstraction that will identify the location and internally use the correct car factory implementation without even giving a single hint to the user. This is exactly the problem, which an abstract factory pattern is used to solve.</p><pre>// Java Program to demonstrate the<br>// working of Abstract Factory Pattern<br><br>enum CarType<br>{<br> MICRO, MINI, LUXURY<br>}<br><br>abstract class Car<br>{<br> Car(CarType model, Location location)<br> {<br>  this.model = model;<br>  this.location = location;<br> }<br><br> abstract void construct();<br><br> CarType model = null;<br> Location location = null;<br><br> CarType getModel()<br> {<br>  return model;<br> }<br><br> void setModel(CarType model)<br> {<br>  this.model = model;<br> }<br><br> Location getLocation()<br> {<br>  return location;<br> }<br><br> void setLocation(Location location)<br> {<br>  this.location = location;<br> }<br><br> @Override<br> public String toString()<br> {<br>  return &quot;CarModel - &quot;+model + &quot; located in &quot;+location;<br> }<br>}<br><br>class LuxuryCar extends Car<br>{<br> LuxuryCar(Location location)<br> {<br>  super(CarType.LUXURY, location);<br>  construct();<br> }<br> @Override<br> protected void construct()<br> {<br>  System.out.println(&quot;Connecting to luxury car&quot;);<br> }<br>}<br><br>class MicroCar extends Car<br>{<br> MicroCar(Location location)<br> {<br>  super(CarType.MICRO, location);<br>  construct();<br> }<br> @Override<br> protected void construct()<br> {<br>  System.out.println(&quot;Connecting to Micro Car &quot;);<br> }<br>}<br><br>class MiniCar extends Car<br>{<br> MiniCar(Location location)<br> {<br>  super(CarType.MINI,location );<br>  construct();<br> }<br> <br> @Override<br> void construct()<br> {<br>  System.out.println(&quot;Connecting to Mini car&quot;);<br> }<br>}<br><br>enum Location<br>{<br>DEFAULT, USA, INDIA<br>}<br><br>class INDIACarFactory<br>{<br> static Car buildCar(CarType model)<br> {<br>  Car car = null;<br>  switch (model)<br>  {<br>   case MICRO:<br>    car = new MicroCar(Location.INDIA);<br>    break;<br>   <br>   case MINI:<br>    car = new MiniCar(Location.INDIA);<br>    break;<br>    <br>   case LUXURY:<br>    car = new LuxuryCar(Location.INDIA);<br>    break;<br>    <br>    default:<br>    break;<br>   <br>  }<br>  return car;<br> }<br>}<br><br>class DefaultCarFactory<br>{<br> public static Car buildCar(CarType model)<br> {<br>  Car car = null;<br>  switch (model)<br>  {<br>   case MICRO:<br>    car = new MicroCar(Location.DEFAULT);<br>    break;<br>   <br>   case MINI:<br>    car = new MiniCar(Location.DEFAULT);<br>    break;<br>    <br>   case LUXURY:<br>    car = new LuxuryCar(Location.DEFAULT);<br>    break;<br>    <br>    default:<br>    break;<br>   <br>  }<br>  return car;<br> }<br>}<br><br><br>class USACarFactory<br>{<br> public static Car buildCar(CarType model)<br> {<br>  Car car = null;<br>  switch (model)<br>  {<br>   case MICRO:<br>    car = new MicroCar(Location.USA);<br>    break;<br>   <br>   case MINI:<br>    car = new MiniCar(Location.USA);<br>    break;<br>    <br>   case LUXURY:<br>    car = new LuxuryCar(Location.USA);<br>    break;<br>    <br>    default:<br>    break;<br>   <br>  }<br>  return car;<br> }<br>}<br><br><br><br>class CarFactory<br>{<br> private CarFactory()<br> {<br>  <br> }<br> public static Car buildCar(CarType type)<br> {<br>  Car car = null;<br>  // We can add any GPS Function here which<br>  // read location property somewhere from configuration<br>  // and use location specific car factory<br>  // Currently I&#39;m just using INDIA as Location<br>  Location location = Location.INDIA;<br>  <br>  switch(location)<br>  {<br>   case USA:<br>    car = USACarFactory.buildCar(type);<br>    break;<br>    <br>   case INDIA:<br>    car = INDIACarFactory.buildCar(type);<br>    break;<br>     <br>   default:<br>    car = DefaultCarFactory.buildCar(type);<br><br>  }<br>  <br>  return car;<br><br> }<br>}<br><br>class AbstractDesign<br>{<br> public static void main(String[] args)<br> {<br>  System.out.println(CarFactory.buildCar(CarType.MICRO));<br>  System.out.println(CarFactory.buildCar(CarType.MINI));<br>  System.out.println(CarFactory.buildCar(CarType.LUXURY));<br> }<br>}</pre><pre>Output :<br><br>Connecting to Micro Car <br>CarModel - MICRO located in INDIA<br>Connecting to Mini car<br>CarModel - MINI located in INDIA<br>Connecting to luxury car<br>CarModel - LUXURY located in INDIA</pre><h4>Intent</h4><ul><li>Separate the construction of a complex object from its representation so that the same construction process can create different representations.</li><li>Parse a complex representation, create one of several targets.</li></ul><h4>Problem</h4><p>An application needs to create the elements of a complex aggregate. The specification for the aggregate exists on secondary storage and one of many representations needs to be built in primary storage.</p><h4>Discussion</h4><p>Separate the algorithm for interpreting (i.e. reading and parsing) a stored persistence mechanism (e.g. RTF files) from the algorithm for building and representing one of many target products (e.g. ASCII, TeX, text widget). The focus/distinction is on creating complex aggregates.</p><p>The “director” invokes “builder” services as it interprets the external format. The “builder” creates part of the complex object each time it is called and maintains all intermediate state. When the product is finished, the client retrieves the result from the “builder”.</p><p>Affords finer control over the construction process. Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the control of the “director”.</p><h4>Structure</h4><p>The Reader encapsulates the parsing of the common input. The Builder hierarchy makes possible the polymorphic creation of many peculiar representations or targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*0OZRSSXq2HE-i6mz" /></figure><h4>Example</h4><p>The Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. This pattern is used by fast food restaurants to construct children’s meals. Children’s meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy dinosaur). Note that there can be variation in the content of the children’s meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*1-pOGJc8J6rVSOvP" /></figure><h3>Factory Method Design Pattern</h3><p>The implementation of Factory Method discussed in the Gang of Four (below) largely overlaps with that of Abstract Factory. For that reason, the presentation in this chapter focuses on the approach that has become popular since.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*w6ojEaTNYr0xDCNV" /></figure><p>An increasingly popular definition of factory method is: a static method of a class that returns an object of that class’ type. But unlike a constructor, the actual object it returns might be an instance of a subclass. Unlike a constructor, an existing object might be reused, instead of a new object created. Unlike a constructor, factory methods can have different and more descriptive names (e.g. Color.make_RGB_color(float red, float green, float blue) and Color.make_HSB_color(float hue, float saturation, float brightness)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*cj0MGOLjXpWfCAurBnUWkQ.png" /></figure><p>The client is totally decoupled from the implementation details of derived classes. Polymorphic creation is now possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*Ghdn8_npWZ0lxF-i" /></figure><h4>Example</h4><p>The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate. Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*vyBZxtQftYJCk6sZm17PpA.png" /></figure><h3>Object Pool Design Pattern</h3><p>Intent<br>Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.</p><h4>Problem</h4><p>Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.</p><p>It is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the Reusable Pool class is designed to be a singleton class.</p><h4>Discussion</h4><p>The Object Pool lets others “check out” objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused.</p><p>However, we don’t want a process to have to wait for a particular object to be released, so the Object Pool also instantiates new objects as they are required, but must also implement a facility to clean up unused objects periodically.</p><h4>Structure</h4><p>The general idea for the Connection Pool pattern is that if instances of a class can be reused, you avoid creating instances of the class by reusing them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*VF7On329Xcp0SprK" /></figure><ul><li>Reusable — Instances of classes in this role collaborate with other objects for a limited amount of time, then they are no longer needed for that collaboration.</li><li>Client — Instances of classes in this role use Reusable objects.</li><li>ReusablePool — Instances of classes in this role manage Reusable objects for use by Client objects.</li></ul><p>Usually, it is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the ReusablePool class is designed to be a singleton class. Its constructor(s) are private, which forces other classes to call its getInstance method to get the one instance of the ReusablePool class.</p><p>A Client object calls a ReusablePool object’s acquireReusable method when it needs a Reusable object. A ReusablePool object maintains a collection of Reusable objects. It uses the collection of Reusable objects to contain a pool of Reusable objects that are not currently in use.</p><p>If there are any Reusable objects in the pool when the acquireReusable method is called, it removes a Reusable object from the pool and returns it. If the pool is empty, then the acquireReusable method creates a Reusable object if it can. If the acquireReusable method cannot create a new Reusable object, then it waits until a Reusable object is returned to the collection.</p><p>Client objects pass a Reusable object to a ReusablePool object’s releaseReusable method when they are finished with the object. The releaseReusable method returns a Reusable object to the pool of Reusable objects that are not in use.</p><p>In many applications of the Object Pool pattern, there are reasons for limiting the total number of Reusable objects that may exist. In such cases, the ReusablePool object that creates Reusable objects is responsible for not creating more than a specified maximum number of Reusable objects. If ReusablePool objects are responsible for limiting the number of objects they will create, then the ReusablePool class will have a method for specifying the maximum number of objects to be created. That method is indicated in the above diagram as setMaxPoolSize.</p><h4>Example</h4><p>Object pool pattern is similar to an office warehouse. When a new employee is hired, office manager has to prepare a work space for him. She figures whether or not there’s a spare equipment in the office warehouse. If so, she uses it. If not, she places an order to purchase new equipment from Amazon. In case if an employee is fired, his equipment is moved to warehouse, where it could be taken when new work place will be needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*36eOIOZ5Im6i3aPX" /></figure><h3>Prototype Design Pattern</h3><h4>Intent</h4><ul><li>Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.</li><li>Co-opt one instance of a class for use as a breeder of all future instances.</li><li>The new operator considered harmful.</li></ul><h4>Problem</h4><p>Application “hard wires” the class of object to create in each “new” expression.</p><h4>Discussion</h4><p>Declare an abstract base class that specifies a pure virtual “clone” method, and, maintains a dictionary of all “cloneable” concrete derived classes. Any class that needs a “polymorphic constructor” capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation.</p><p>The client then, instead of writing code that invokes the “new” operator on a hard-wired class name, calls a “clone” operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.</p><h4>Structure</h4><p>The Factory knows how to find the correct Prototype, and each Product knows how to spawn new instances of itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*5fj8q0qLTDGu5JKE" /></figure><h4>Example</h4><p>The Prototype pattern specifies the kind of objects to create using a prototypical instance. Prototypes of new products are often built prior to full production, but in this example, the prototype is passive and does not participate in copying itself. The mitotic division of a cell — resulting in two identical cells — is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*yvRj2ggFvn5__COt" /></figure><pre>// A Java program to demonstrate working of<br>// Prototype Design Pattern with example<br>// of a ColorStore class to store existing objects.<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>// Cloneable interface allows the implementing class to<br>// have its objects to be cloned instead of using a new operator.<br>// It is available in Java.lang.Cloneable.<br><br>abstract class Color implements Cloneable<br>{<br> <br> protected String colorName;<br> <br> abstract void addColor();<br> <br> public Object clone()<br> {<br>  Object clone = null;<br>  try<br>  {<br>   clone = super.clone();<br>  }<br>  catch (CloneNotSupportedException e)<br>  {<br>   e.printStackTrace();<br>  }<br>  return clone;<br> }<br>}<br><br>class blueColor extends Color<br>{<br> public blueColor()<br> {<br>  this.colorName = &quot;blue&quot;;<br> }<br><br> @Override<br> void addColor()<br> {<br>  System.out.println(&quot;Blue color added&quot;);<br> }<br> <br>}<br><br>class blackColor extends Color{<br><br> public blackColor()<br> {<br>  this.colorName = &quot;black&quot;;<br> }<br><br> @Override<br> void addColor()<br> {<br>  System.out.println(&quot;Black color added&quot;);<br> }<br>}<br><br>class ColorStore {<br><br> private static Map&lt;String, Color&gt; colorMap = new HashMap&lt;String, Color&gt;();<br> <br> static<br> {<br>  colorMap.put(&quot;blue&quot;, new blueColor());<br>  colorMap.put(&quot;black&quot;, new blackColor());<br> }<br> <br> public static Color getColor(String colorName)<br> {<br>  return (Color) colorMap.get(colorName).clone();<br> }<br>}<br><br><br>// Driver class<br>class Prototype<br>{<br> public static void main (String[] args)<br> {<br>  ColorStore.getColor(&quot;blue&quot;).addColor();<br>  ColorStore.getColor(&quot;black&quot;).addColor();<br>  ColorStore.getColor(&quot;black&quot;).addColor();<br>  ColorStore.getColor(&quot;blue&quot;).addColor();<br> }<br>}</pre><pre>Output: <br><br>Blue color added<br>Black color added<br>Black color added<br>Blue color added</pre><h3>Singleton Design Pattern</h3><h4>Intent</h4><ul><li>Ensure a class has only one instance, and provide a global point of access to it.</li><li>Encapsulated “just-in-time initialization” or “initialization on first use”.</li></ul><h4>Problem</h4><p>Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.</p><h4>Discussion</h4><p>Make the class of the single instance object responsible for creation, initialization, access, and enforcement. Declare the instance as a private static data member. Provide a public static member function that encapsulates all initialization code, and provides access to the instance.</p><p>The client calls the accessor function (using the class name and scope resolution operator) whenever a reference to the single instance is required.</p><p>Singleton should be considered only if all three of the following criteria are satisfied:</p><ul><li>Ownership of the single instance cannot be reasonably assigned</li><li>Lazy initialization is desirable</li><li>Global access is not otherwise provided for</li></ul><p>If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting.</p><p>The Singleton pattern can be extended to support access to an application-specific number of instances.</p><p>The “static member function accessor” approach will not support subclassing of the Singleton class. If subclassing is desired, refer to the discussion in the book.</p><p>Deleting a Singleton class/instance is a non-trivial design problem. See “To Kill A Singleton” by John Vlissides for a discussion.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*io9zhLfptf5QSOYn" /></figure><p>Make the class of the single instance responsible for access and “initialization on first use”. The single instance is a private static attribute. The accessor function is a public static method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*ClpswFTC5b0P5tui" /></figure><h4>Example</h4><p>The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, “The President of the United States” is a global point of access that identifies the person in the office.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*FML-HgJhDjhuVpWp" /></figure><h4>Method 1: Classic Implementation</h4><pre>// Classical Java implementation of singleton<br>// design pattern<br>class Singleton<br>{<br> private static Singleton obj;<br><br> // private constructor to force use of<br> // getInstance() to create Singleton object<br> private Singleton() {}<br><br> public static Singleton getInstance()<br> {<br>  if (obj==null)<br>   obj = new Singleton();<br>  return obj;<br> }<br>}</pre><h4>Method 2: Make getInstance() synchronized</h4><pre>// Thread Synchronized Java implementation of<br>// singleton design pattern<br>class Singleton<br>{<br> private static Singleton obj;<br> private Singleton() {}<br><br> // Only one thread can execute this at a time<br> public static synchronized Singleton getInstance()<br> {<br>  if (obj==null)<br>   obj = new Singleton();<br>  return obj;<br> }<br>}</pre><p>Method 3: Eager Instantiation</p><pre>// Static initializer based Java implementation of<br>// singleton design pattern<br>class Singleton<br>{<br> private static Singleton obj = new Singleton();<br> private Singleton() {}<br><br> public static Singleton getInstance()<br> {<br>  return obj;<br> }<br>}</pre><h3>Structural patterns</h3><p>In Software Engineering, Structural Design Patterns are Design Patterns that ease the design by identifying a simple way to realize relationships between entities.</p><h3>Adapter Design Pattern</h3><h4>Intent</h4><ul><li>Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.</li><li>Wrap an existing class with a new interface.</li><li>Impedance match an old component to a new system</li></ul><h4>Problem</h4><p>An “off the shelf” component offers compelling functionality that you would like to reuse, but its “view of the world” is not compatible with the philosophy and architecture of the system currently being developed.</p><h4>Discussion</h4><p>Reuse has always been painful and elusive. One reason has been the tribulation of designing something new, while reusing something old. There is always something not quite right between the old and the new. It may be physical dimensions or misalignment. It may be timing or synchronization. It may be unfortunate assumptions or competing standards.</p><p>It is like the problem of inserting a new three-prong electrical plug in an old two-prong wall outlet — some kind of adapter or intermediary is necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*B3JVn2IKY_c_drZC" /></figure><p>Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system. Clients call methods on the Adapter object which redirects them into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation.</p><p>Adapter functions as a wrapper or modifier of an existing class. It provides a different or translated view of that class.</p><h4>Structure</h4><p>Below, a legacy Rectangle component’s display() method expects to receive “x, y, w, h” parameters. But the client wants to pass “upper left x and y” and “lower right x and y”. This incongruity can be reconciled by adding an additional level of indirection — i.e. an Adapter object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*tKiK-lJpJ0nWyV40" /></figure><p>The Adapter could also be thought of as a “wrapper”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*V0yMIn9to6vAZ7aY" /></figure><h4>Example</h4><p>The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients. Socket wrenches provide an example of the Adapter. A socket attaches to a ratchet, provided that the size of the drive is the same. Typical drive sizes in the United States are 1/2&quot; and 1/4&quot;. Obviously, a 1/2&quot; drive ratchet will not fit into a 1/4&quot; drive socket unless an adapter is used. A 1/2&quot; to 1/4&quot; adapter has a 1/2&quot; female connection to fit on the 1/2&quot; drive ratchet, and a 1/4&quot; male connection to fit in the 1/4&quot; drive socket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*jt1_phbaXC4ujY-3" /></figure><h3>Bridge Design Pattern</h3><h4>Intent</h4><ul><li>Decouple an abstraction from its implementation so that the two can vary independently.</li><li>Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy.</li><li>Beyond encapsulation, to insulation</li></ul><h4>Problem</h4><p>“Hardening of the software arteries” has occurred by using subclassing of an abstract base class to provide alternative implementations. This locks in compile-time binding between interface and implementation. The abstraction and implementation cannot be independently extended or composed.</p><h4>Motivation</h4><p>Consider the domain of “thread scheduling”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*5veEDhY92n7dLzxK" /></figure><p>There are two types of thread schedulers, and two types of operating systems or “platforms”. Given this approach to specialization, we have to define a class for each permutation of these two dimensions. If we add a new platform (say … Java’s Virtual Machine), what would our hierarchy look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*JbqKE9wb8wbCvB_KjPcRnA.png" /></figure><p>What if we had three kinds of thread schedulers, and four kinds of platforms? What if we had five kinds of thread schedulers, and ten kinds of platforms? The number of classes we would have to define is the product of the number of scheduling schemes and the number of platforms.</p><p>The Bridge design pattern proposes refactoring this exponentially explosive inheritance hierarchy into two orthogonal hierarchies — one for platform-independent abstractions, and the other for platform-dependent implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*ToUEtlldV23UT_ld" /></figure><h4>Discussion</h4><p>Decompose the component’s interface and implementation into orthogonal class hierarchies. The interface class contains a pointer to the abstract implementation class. This pointer is initialized with an instance of a concrete implementation class, but all subsequent interaction from the interface class to the implementation class is limited to the abstraction maintained in the implementation base class. The client interacts with the interface class, and it in turn “delegates” all requests to the implementation class.</p><p>The interface object is the “handle” known and used by the client; while the implementation object, or “body”, is safely encapsulated to ensure that it may continue to evolve, or be entirely replaced (or shared at run-time.</p><p>Use the Bridge pattern when:</p><ul><li>you want run-time binding of the implementation,</li><li>you have a proliferation of classes resulting from a coupled interface and numerous implementations,</li><li>you want to share an implementation among multiple objects,</li><li>you need to map orthogonal class hierarchies.</li></ul><p>Consequences include:</p><ul><li>decoupling the object’s interface,</li><li>improved extensibility (you can extend (i.e. subclass) the abstraction and implementation hierarchies independently),</li><li>hiding details from clients.</li></ul><p>Bridge is a synonym for the “handle/body” idiom. This is a design mechanism that encapsulates an implementation class inside of an interface class. The former is the body, and the latter is the handle. The handle is viewed by the user as the actual class, but the work is done in the body. “The handle/body class idiom may be used to decompose a complex abstraction into smaller, more manageable classes. The idiom may reflect the sharing of a single resource by multiple classes that control access to it (e.g. reference counting).”</p><h4>Structure</h4><p>The Client doesn’t want to deal with platform-dependent details. The Bridge pattern encapsulates this complexity behind an abstraction “wrapper”.</p><p>Bridge emphasizes identifying and decoupling “interface” abstraction from “implementation” abstraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*DGyYg_Q_fPYCWeQo" /></figure><h4>Example</h4><p>The Bridge pattern decouples an abstraction from its implementation, so that the two can vary independently. A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be implemented as a pull chain, simple two position switch, or a variety of dimmer switches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*-_GRbHMMApqqlwnq" /></figure><p>Lets see an Example of Bridge Design Pattern</p><pre>// Java code to demonstrate<br>// bridge design pattern<br><br>// abstraction in bridge pattern<br>abstract class Vehicle {<br> protected Workshop workShop1;<br> protected Workshop workShop2;<br><br> protected Vehicle(Workshop workShop1, Workshop workShop2)<br> {<br>  this.workShop1 = workShop1;<br>  this.workShop2 = workShop2;<br> }<br><br> abstract public void manufacture();<br>}<br><br>// Refine abstraction 1 in bridge pattern<br>class Car extends Vehicle {<br> public Car(Workshop workShop1, Workshop workShop2)<br> {<br>  super(workShop1, workShop2);<br> }<br><br> @Override<br> public void manufacture()<br> {<br>  System.out.print(&quot;Car &quot;);<br>  workShop1.work();<br>  workShop2.work();<br> }<br>}<br><br>// Refine abstraction 2 in bridge pattern<br>class Bike extends Vehicle {<br> public Bike(Workshop workShop1, Workshop workShop2)<br> {<br>  super(workShop1, workShop2);<br> }<br><br> @Override<br> public void manufacture()<br> {<br>  System.out.print(&quot;Bike &quot;);<br>  workShop1.work();<br>  workShop2.work();<br> }<br>}<br><br>// Implementer for bridge pattern<br>interface Workshop<br>{<br> abstract public void work();<br>}<br><br>// Concrete implementation 1 for bridge pattern<br>class Produce implements Workshop {<br> @Override<br> public void work()<br> {<br>  System.out.print(&quot;Produced&quot;);<br> }<br>}<br><br>// Concrete implementation 2 for bridge pattern<br>class Assemble implements Workshop {<br> @Override<br> public void work()<br> {<br>  System.out.print(&quot; And&quot;);<br>  System.out.println(&quot; Assembled.&quot;);<br> }<br>}<br><br>// Demonstration of bridge design pattern<br>class BridgePattern {<br> public static void main(String[] args)<br> {<br>  Vehicle vehicle1 = new Car(new Produce(), new Assemble());<br>  vehicle1.manufacture();<br>  Vehicle vehicle2 = new Bike(new Produce(), new Assemble());<br>  vehicle2.manufacture();<br> }<br>}</pre><pre>Output : <br><br>Car Produced And Assembled.<br>Bike Produced And Assembled.</pre><h3>Composite Design Pattern</h3><h4>Intent</h4><ul><li>Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.</li><li>Recursive composition</li><li>“Directories contain entries, each of which could be a directory.”</li><li>1-to-many “has a” up the “is a” hierarchy</li></ul><h4>Problem</h4><p>Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.</p><h4>Discussion</h4><p>Define an abstract base class (Component) that specifies the behavior that needs to be exercised uniformly across all primitive and composite objects. Subclass the Primitive and Composite classes off of the Component class. Each Composite object “couples” itself only to the abstract type Component as it manages its “children”.</p><p>Use this pattern whenever you have “composites that contain components, each of which could be a composite”.</p><p>Child management methods [e.g. addChild(), removeChild()] should normally be defined in the Composite class. Unfortunately, the desire to treat Primitives and Composites uniformly requires that these methods be moved to the abstract Component class. See the “Opinions” section below for a discussion of “safety” versus “transparency” issues.</p><h4>Structure</h4><p>Composites that contain Components, each of which could be a Composite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/0*VoURkML7SE7cmYg4" /></figure><p>Menus that contain menu items, each of which could be a menu.</p><p>Row-column GUI layout managers that contain widgets, each of which could be a row-column GUI layout manager.</p><p>Directories that contain files, each of which could be a directory.</p><p>Containers that contain Elements, each of which could be a Container.</p><h4>Example</h4><p>The Composite composes objects into tree structures and lets clients treat individual objects and compositions uniformly. Although the example is abstract, arithmetic expressions are Composites. An arithmetic expression consists of an operand, an operator (+ — * /), and another operand. The operand can be a number, or another arithmetic expression. Thus, 2 + 3 and (2 + 3) + (4 * 6) are both valid expressions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*MyR-5W7BnORUzq-v" /></figure><h3>Decorator Design Pattern</h3><h4>Intent</h4><ul><li>Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.</li><li>Client-specified embellishment of a core object by recursively wrapping it.</li><li>Wrapping a gift, putting it in a box, and wrapping the box.</li></ul><h4>Problem</h4><p>You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.</p><h4>Discussion</h4><p>Suppose you are working on a user interface toolkit and you wish to support adding borders and scroll bars to windows. You could define an inheritance hierarchy like …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*7yQgtfoJrYbSQYol" /></figure><p>But the Decorator pattern suggests giving the client the ability to specify whatever combination of “features” is desired.</p><p>Widget* aWidget = new BorderDecorator(</p><p>new HorizontalScrollBarDecorator(</p><p>new VerticalScrollBarDecorator(</p><p>new Window( 80, 24 ))));</p><p>aWidget-&gt;draw();</p><p>This flexibility can be achieved with the following design</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*AY-gL2XHu3Y3du3C0G6dJQ.png" /></figure><p>Another example of cascading (or chaining) features together to produce a custom object might look like …</p><p>Stream* aStream = new CompressingStream(</p><p>new ASCII7Stream(</p><p>new FileStream(“fileName.dat”)));</p><p>aStream-&gt;putString( “Hello world” );</p><p>The solution to this class of problems involves encapsulating the original object inside an abstract wrapper interface. Both the decorator objects and the core object inherit from this abstract interface. The interface uses recursive composition to allow an unlimited number of decorator “layers” to be added to each core object.</p><p>Note that this pattern allows responsibilities to be added to an object, not methods to an object’s interface. The interface presented to the client must remain constant as successive layers are specified.</p><p>Also note that the core object’s identity has now been “hidden” inside of a decorator object. Trying to access the core object directly is now a problem.</p><h4>Structure</h4><p>The client is always interested in CoreFunctionality.doThis(). The client may, or may not, be interested in OptionalOne.doThis() and OptionalTwo.doThis(). Each of these classes always delegate to the Decorator base class, and that class always delegates to the contained “wrappee” object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*lW-iBCYIOHMijtiK" /></figure><h4>Example</h4><p>The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc., can be added to a tree to give it a festive look. The ornaments do not change the tree itself which is recognizable as a Christmas tree regardless of particular ornaments used. As an example of additional functionality, the addition of lights allows one to “light up” a Christmas tree.</p><p>Another example: assault gun is a deadly weapon on it’s own. But you can apply certain “decorations” to make it more accurate, silent and devastating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*uTwNXJ0tREXTYkkR" /></figure><p>The getCost() of superclass calculates the costs for all the toppings while the one in the subclass adds the cost of that specific pizza.</p><pre>// Sample getCost() in super class<br>public int getCost()<br>{<br>    int totalToppingsCost = 0;<br>    if (hasJalapeno() )<br>        totalToppingsCost += jalapenoCost;<br>    if (hasCapsicum() )<br>        totalToppingsCost += capsicumCost;<br><br>    // similarly for other toppings<br>    return totalToppingsCost;<br>}</pre><pre>// Sample getCost() in subclass<br>public int getCost()<br>{<br>    // 100 for Margherita and super.getCost()<br>    // for toppings.<br>    return super.getCost() + 100;<br>}</pre><h3>Facade Design Pattern</h3><h4>Intent</h4><ul><li>Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.</li><li>Wrap a complicated subsystem with a simpler interface.</li></ul><h4>Problem</h4><p>A segment of the client community needs a simplified interface to the overall functionality of a complex subsystem.</p><h4>Discussion</h4><p>Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. It also promotes decoupling the subsystem from its potentially many clients. On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that “power users” may need.</p><p>The Facade object should be a fairly simple advocate or facilitator. It should not become an all-knowing oracle or “god” object.</p><h4>Structure</h4><p>Facade takes a “riddle wrapped in an enigma shrouded in mystery”, and interjects a wrapper that tames the amorphous and inscrutable mass of software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*UuYRtUfynJyaAPlo" /></figure><p>SubsystemOne and SubsystemThree do not interact with the internal components of SubsystemTwo. They use the SubsystemTwoWrapper “facade” (i.e. the higher level abstraction).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*y2jxxMUk4Cav7fTx" /></figure><h4>Example</h4><p>The Facade defines a unified, higher level interface to a subsystem that makes it easier to use. Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*4_flftt8Q7bAs-VP" /></figure><h3>Flyweight Design Pattern</h3><h4>Intent</h4><ul><li>Use sharing to support large numbers of fine-grained objects efficiently.</li><li>The Motif GUI strategy of replacing heavy-weight widgets with light-weight gadgets.</li></ul><h4>Problem</h4><p>Designing objects down to the lowest levels of system “granularity” provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage.</p><h4>Discussion</h4><p>The Flyweight pattern describes how to share objects to allow their use at fine granularity without prohibitive cost. Each “flyweight” object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.</p><p>An illustration of this approach would be Motif widgets that have been re-engineered as light-weight gadgets. Whereas widgets are “intelligent” enough to stand on their own; gadgets exist in a dependent relationship with their parent layout manager widget. Each layout manager provides context-dependent event handling, real estate management, and resource services to its flyweight gadgets, and each gadget is only responsible for context-independent state and behavior.</p><h4>Structure</h4><p>Flyweights are stored in a Factory’s repository. The client restrains herself from creating Flyweights directly, and requests them from the Factory. Each Flyweight cannot stand on its own. Any attributes that would make sharing impossible must be supplied by the client whenever a request is made of the Flyweight. If the context lends itself to “economy of scale” (i.e. the client can easily compute or look-up the necessary attributes), then the Flyweight pattern offers appropriate leverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*gMC6AJKqNXEUOa2YC_v2OQ.png" /></figure><p>The Ant, Locust, and Cockroach classes can be “light-weight” because their instance-specific state has been de-encapsulated, or externalized, and must be supplied by the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*jlvZbRgPMBi6T6bPGgE0Cw.png" /></figure><h4>Example</h4><p>The Flyweight uses sharing to support large numbers of objects efficiently. Modern web browsers use this technique to prevent loading same images twice. When browser loads a web page, it traverse through all images on that page. Browser loads all new images from Internet and places them the internal cache. For already loaded images, a flyweight object is created, which has some unique data like position within the page, but everything else is referenced to the cached one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*0D38qBKYW9iPCXo5fY4boA.png" /></figure><h3>Private Class Data</h3><h4>Intent</h4><ul><li>Control write access to class attributes</li><li>Separate data from methods that use it</li><li>Encapsulate class data initialization</li><li>Providing new type of final — final after constructor</li></ul><h4>Problem</h4><p>A class may expose its attributes (class variables) to manipulation when manipulation is no longer desirable, e.g. after construction. Using the private class data design pattern prevents that undesirable manipulation.</p><p>A class may have one-time mutable attributes that cannot be declared final. Using this design pattern allows one-time setting of those class attributes.</p><p>The motivation for this design pattern comes from the design goal of protecting class state by minimizing the visibility of its attributes (data).</p><h4>Discussion</h4><p>The private class data design pattern seeks to reduce exposure of attributes by limiting their visibility.</p><p>It reduces the number of class attributes by encapsulating them in single Data object. It allows the class designer to remove write privilege of attributes that are intended to be set only during construction, even from methods of the target class.</p><h4>Structure</h4><p>The private class data design pattern solves the problems above by extracting a data class for the target class and giving the target class instance an instance of the extracted data class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*ONpzthUj9V3Zf76rcB1Kkw.png" /></figure><h3>Proxy Design Pattern</h3><h4>Intent</h4><ul><li>Provide a surrogate or placeholder for another object to control access to it.</li><li>Use an extra level of indirection to support distributed, controlled, or intelligent access.</li><li>Add a wrapper and delegation to protect the real component from undue complexity.</li></ul><h4>Problem</h4><p>You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.</p><h4>Discussion</h4><p>Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object.</p><p>There are four common situations in which the Proxy pattern is applicable.</p><ol><li>A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object.</li><li>A remote proxy provides a local representative for an object that resides in a different address space. This is what the “stub” code in RPC and CORBA provides.</li><li>A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.</li><li>A smart proxy interposes additional actions when an object is accessed. Typical uses include:</li></ol><ul><li>Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer)</li><li>Loading a persistent object into memory when it’s first referenced.</li><li>Checking that the real object is locked before it is accessed to ensure that no other object can change it.</li></ul><h4>Structure</h4><p>By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Aom1rRxOeFoCWeu_7Gs7ag.png" /></figure><h4>Example</h4><p>The Proxy provides a surrogate or place holder to provide access to an object. A check or bank draft is a proxy for funds in an account. A check can be used in place of cash for making purchases and ultimately controls access to cash in the issuer’s account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*9VOdU2Y85vMlzGAtJ8OM_Q.png" /></figure><h3>Behavioral patterns</h3><p>In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.</p><p>Chain of responsibility</p><ul><li>A way of passing a request between a chain of objects</li></ul><p>Command</p><ul><li>Encapsulate a command request as an object</li></ul><p>Interpreter</p><ul><li>A way to include language elements in a program</li></ul><p>Iterator</p><ul><li>Sequentially access the elements of a collection</li></ul><p>Mediator</p><ul><li>Defines simplified communication between classes</li></ul><p>Memento</p><ul><li>Capture and restore an object’s internal state</li></ul><p>Null Object</p><ul><li>Designed to act as a default value of an object</li></ul><p>Observer</p><ul><li>A way of notifying change to a number of classes</li></ul><p>State</p><ul><li>Alter an object’s behavior when its state changes</li></ul><p>Strategy</p><ul><li>Encapsulates an algorithm inside a class</li></ul><p>Template method</p><ul><li>Defer the exact steps of an algorithm to a subclass</li></ul><p>Visitor</p><ul><li>Defines a new operation to a class without change</li></ul><h3>Chain of Responsibility</h3><h4>Intent</h4><ul><li>Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.</li><li>Launch-and-leave requests with a single processing pipeline that contains many possible handlers.</li><li>An object-oriented linked list with recursive traversal.</li></ul><h4>Problem</h4><p>There is a potentially variable number of “handler” or “processing element” or “node” objects, and a stream of requests that must be handled. Need to efficiently process the requests without hard-wiring handler relationships and precedence, or request-to-handler mappings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*yTnpvqqXwJqwvYZD" /></figure><h4>Discussion</h4><p>Encapsulate the processing elements inside a “pipeline” abstraction; and have clients “launch and leave” their requests at the entrance to the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*aespFonZXlHlDxhP7BSX2Q.png" /></figure><p>The pattern chains the receiving objects together, and then passes any request messages from object to object until it reaches an object capable of handling the message. The number and type of handler objects isn’t known a priori, they can be configured dynamically. The chaining mechanism uses recursive composition to allow an unlimited number of handlers to be linked.</p><p>Chain of Responsibility simplifies object interconnections. Instead of senders and receivers maintaining references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain.</p><p>Make sure there exists a “safety net” to “catch” any requests which go unhandled.</p><p>Do not use Chain of Responsibility when each request is only handled by one handler, or, when the client object knows which service object should handle the request.</p><h4>Structure</h4><p>The derived classes know how to satisfy Client requests. If the “current” object is not available or sufficient, then it delegates to the base class, which delegates to the “next” object, and the circle of life continues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*65yWk2Jfl1e2AiaCwNQfYg.png" /></figure><p>Multiple handlers could contribute to the handling of each request. The request can be passed down the entire length of the chain, with the last link being careful not to delegate to a “null next”.</p><h4>Example</h4><p>The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver by giving more than one object a chance to handle the request. ATM use the Chain of Responsibility in money giving mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*r3NweeBnREMGb6Lh" /></figure><p>How to send a request in the application using the Chain of Responsibility</p><p>The Client in need of a request to be handled sends it to the chain of handlers which are classes that extend the Handler class.</p><p>Each of the handlers in the chain takes its turn trying to handle the request it receives from the client.</p><p>If ConcreteHandler1 can handle it, then the request is handled, if not it is sent to the handler ConcreteHandler2, the next one in the chain.</p><p>Let’s see an Example of Chain of Responsibility Design Pattern:</p><pre>public class Chain<br>{<br>Processor chain;<br><br>public Chain(){<br> buildChain();<br>}<br><br>private void buildChain(){<br> chain = new NegativeProcessor(new ZeroProcessor(new PositiveProcessor(null)));<br>}<br><br>public void process(Number request) {<br> chain.process(request);<br>}<br><br>}<br><br>abstract class Processor<br>{<br> private Processor nextProcessor;<br><br> public Processor(Processor nextProcessor){<br>  this.nextProcessor = nextProcessor;<br> };<br> <br> public void process(Number request){<br>  if(nextProcessor != null)<br>   nextProcessor.process(request);<br> };<br>}<br><br>class Number<br>{<br> private int number;<br><br> public Number(int number)<br> {<br>  this.number = number;<br> }<br><br> public int getNumber()<br> {<br>  return number;<br> }<br><br>}<br><br>class NegativeProcessor extends Processor<br>{<br> public NegativeProcessor(Processor nextProcessor){<br>  super(nextProcessor);<br>  <br> }<br><br> public void process(Number request)<br> {<br>  if (request.getNumber() &lt; 0)<br>  {<br>   System.out.println(&quot;NegativeProcessor : &quot; + request.getNumber());<br>  }<br>  else<br>  {<br>   super.process(request);<br>  }<br> }<br>}<br><br>class ZeroProcessor extends Processor<br>{<br> public ZeroProcessor(Processor nextProcessor){<br>  super(nextProcessor);<br> }<br><br> public void process(Number request)<br> {<br>  if (request.getNumber() == 0)<br>  {<br>   System.out.println(&quot;ZeroProcessor : &quot; + request.getNumber());<br>  }<br>  else<br>  {<br>   super.process(request);<br>  }<br> }<br>}<br><br>class PositiveProcessor extends Processor<br>{<br><br> public PositiveProcessor(Processor nextProcessor){<br>  super(nextProcessor);<br> }<br><br> public void process(Number request)<br> {<br>  if (request.getNumber() &gt; 0)<br>  {<br>   System.out.println(&quot;PositiveProcessor : &quot; + request.getNumber());<br>  }<br>  else<br>  {<br>   super.process(request);<br>  }<br> }<br>}<br><br>class TestChain<br>{<br> public static void main(String[] args) {<br>  Chain chain = new Chain();<br>  <br>  //Calling chain of responsibility<br>  chain.process(new Number(90));<br>  chain.process(new Number(-50));<br>  chain.process(new Number(0));<br>  chain.process(new Number(91));<br> }<br>}</pre><pre>Output: <br>PositiveProcessor : 90<br>NegativeProcessor : -50<br>ZeroProcessor : 0<br>PositiveProcessor : 91</pre><h3>Command Design Pattern</h3><h4>Intent</h4><ul><li>Encapsulate a request as an object, thereby letting you parametrize clients with different requests, queue or log requests, and support undoable operations.</li><li>Promote “invocation of a method on an object” to full object status</li><li>An object-oriented callback</li></ul><h4>Problem</h4><p>Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.</p><h4>Discussion</h4><p>Command decouples the object that invokes the operation from the one that knows how to perform it. To achieve this separation, the designer creates an abstract base class that maps a receiver (an object) with an action (a pointer to a member function). The base class contains an execute() method that simply calls the action on the receiver.</p><p>All clients of Command objects treat each object as a “black box” by simply invoking the object’s virtual execute() method whenever the client requires the object’s “service”.</p><p>A Command class holds some subset of the following: an object, a method to be applied to the object, and the arguments to be passed when the method is applied. The Command’s “execute” method then causes the pieces to come together.</p><p>Sequences of Command objects can be assembled into composite (or macro) commands.</p><h4>Structure</h4><p>The client that creates a command is not the same client that executes it. This separation provides flexibility in the timing and sequencing of commands. Materializing commands as objects means they can be passed, staged, shared, loaded in a table, and otherwise instrumented or manipulated like any other object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*8DmyQ4aUtysy4P4Q" /></figure><p>Command objects can be thought of as “tokens” that are created by one client that knows what need to be done, and passed to another client that has the resources for doing it.</p><h4>Example</h4><p>The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests. The “check” at a diner is an example of a Command pattern. The waiter or waitress takes an order or command from a customer and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of “checks” used by each waiter is not dependent on the menu, and therefore they can support commands to cook many different items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*HcnWbwvB-6blcntF" /></figure><pre>// A simple Java program to demonstrate<br>// implementation of Command Pattern using<br>// a remote control example.<br><br>// An interface for command<br>interface Command<br>{<br> public void execute();<br>}<br><br>// Light class and its corresponding command<br>// classes<br>class Light<br>{<br> public void on()<br> {<br>  System.out.println(&quot;Light is on&quot;);<br> }<br> public void off()<br> {<br>  System.out.println(&quot;Light is off&quot;);<br> }<br>}<br>class LightOnCommand implements Command<br>{<br> Light light;<br><br> // The constructor is passed the light it<br> // is going to control.<br> public LightOnCommand(Light light)<br> {<br> this.light = light;<br> }<br> public void execute()<br> {<br> light.on();<br> }<br>}<br>class LightOffCommand implements Command<br>{<br> Light light;<br> public LightOffCommand(Light light)<br> {<br>  this.light = light;<br> }<br> public void execute()<br> {<br>  light.off();<br> }<br>}<br><br>// Stereo and its command classes<br>class Stereo<br>{<br> public void on()<br> {<br>  System.out.println(&quot;Stereo is on&quot;);<br> }<br> public void off()<br> {<br>  System.out.println(&quot;Stereo is off&quot;);<br> }<br> public void setCD()<br> {<br>  System.out.println(&quot;Stereo is set &quot; +<br>      &quot;for CD input&quot;);<br> }<br> public void setDVD()<br> {<br>  System.out.println(&quot;Stereo is set&quot;+<br>      &quot; for DVD input&quot;);<br> }<br> public void setRadio()<br> {<br>  System.out.println(&quot;Stereo is set&quot; +<br>      &quot; for Radio&quot;);<br> }<br> public void setVolume(int volume)<br> {<br> // code to set the volume<br> System.out.println(&quot;Stereo volume set&quot;<br>      + &quot; to &quot; + volume);<br> }<br>}<br>class StereoOffCommand implements Command<br>{<br> Stereo stereo;<br> public StereoOffCommand(Stereo stereo)<br> {<br>  this.stereo = stereo;<br> }<br> public void execute()<br> {<br> stereo.off();<br> }<br>}<br>class StereoOnWithCDCommand implements Command<br>{<br> Stereo stereo;<br> public StereoOnWithCDCommand(Stereo stereo)<br> {<br>  this.stereo = stereo;<br> }<br> public void execute()<br> {<br>  stereo.on();<br>  stereo.setCD();<br>  stereo.setVolume(11);<br> }<br>}<br><br>// A Simple remote control with one button<br>class SimpleRemoteControl<br>{<br> Command slot; // only one button<br><br> public SimpleRemoteControl()<br> {<br> }<br><br> public void setCommand(Command command)<br> {<br>  // set the command the remote will<br>  // execute<br>  slot = command;<br> }<br><br> public void buttonWasPressed()<br> {<br>  slot.execute();<br> }<br>}<br><br>// Driver class<br>class RemoteControlTest<br>{<br> public static void main(String[] args)<br> {<br>  SimpleRemoteControl remote =<br>    new SimpleRemoteControl();<br>  Light light = new Light();<br>  Stereo stereo = new Stereo();<br><br>  // we can change command dynamically<br>  remote.setCommand(new<br>     LightOnCommand(light));<br>  remote.buttonWasPressed();<br>  remote.setCommand(new<br>    StereoOnWithCDCommand(stereo));<br>  remote.buttonWasPressed();<br>  remote.setCommand(new<br>    StereoOffCommand(stereo));<br>  remote.buttonWasPressed();<br> }<br>}</pre><pre>Output:<br><br>Light is on<br>Stereo is on<br>Stereo is set for CD input<br>Stereo volume set to 11<br>Stereo is off</pre><h3>Interpreter Design Pattern</h3><h4>Intent</h4><ul><li>Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.</li><li>Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.</li></ul><h4>Problem</h4><p>A class of problems occurs repeatedly in a well-defined and well-understood domain. If the domain were characterized with a “language”, then problems could be easily solved with an interpretation “engine”.</p><h4>Discussion</h4><p>The Interpreter pattern discusses: defining a domain language (i.e. problem characterization) as a simple language grammar, representing domain rules as language sentences, and interpreting these sentences to solve the problem. The pattern uses a class to represent each grammar rule. And since grammars are usually hierarchical in structure, an inheritance hierarchy of rule classes maps nicely.</p><p>An abstract base class specifies the method interpret(). Each concrete subclass implements interpret() by accepting (as an argument) the current state of the language stream, and adding its contribution to the problem solving process.</p><h4>Structure</h4><p>Interpreter suggests modeling the domain with a recursive grammar. Each rule in the grammar is either a ‘composite’ (a rule that references other rules) or a terminal (a leaf node in a tree structure). Interpreter relies on the recursive traversal of the Composite pattern to interpret the ‘sentences’ it is asked to process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*pSiFh5_gg8EDXevajRg5gw.png" /></figure><h4>Example</h4><p>The Interpreter pattern defines a grammatical representation for a language and an interpreter to interpret the grammar. Musicians are examples of Interpreters. The pitch of a sound and its duration can be represented in musical notation on a staff. This notation provides the language of music. Musicians playing the music from the score are able to reproduce the original pitch and duration of each sound represented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*kuiNDVag4goWkcVo" /></figure><h3>Iterator Design Pattern</h3><h4>Intent</h4><ul><li>Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.</li><li>The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms.</li><li>Promote to “full object status” the traversal of a collection.</li><li>Polymorphic traversal</li></ul><h4>Problem</h4><p>Need to “abstract” the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently.</p><h4>Discussion</h4><p>“An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you need to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you’ll require. You might also need to have more than one traversal pending on the same list.” And, providing a uniform interface for traversing many types of aggregate objects (i.e. polymorphic iteration) might be valuable.</p><p>The Iterator pattern lets you do all this. The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol.</p><p>The Iterator abstraction is fundamental to an emerging technology called “generic programming”. This strategy seeks to explicitly separate the notion of “algorithm” from that of “data structure”. The motivation is to: promote component-based development, boost productivity, and reduce configuration management.</p><p>As an example, if you wanted to support four data structures (array, binary tree, linked list, and hash table) and three algorithms (sort, find, and merge), a traditional approach would require four times three permutations to develop and maintain. Whereas, a generic programming approach would only require four plus three configuration items.</p><h4>Structure</h4><p>The Client uses the Collection class’ public interface directly. But access to the Collection’s elements is encapsulated behind the additional level of abstraction called Iterator. Each Collection derived class knows which Iterator derived class to create and return. After that, the Client relies on the interface defined in the Iterator base class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*_w4qLwlJNWEH5iZE" /></figure><h4>Example</h4><p>The Iterator provides ways to access elements of an aggregate object sequentially without exposing the underlying structure of the object. Files are aggregate objects. In office settings where access to files is made through administrative or secretarial staff, the Iterator pattern is demonstrated with the secretary acting as the Iterator. Several television comedy skits have been developed around the premise of an executive trying to understand the secretary’s filing system. To the executive, the filing system is confusing and illogical, but the secretary is able to access files quickly and efficiently.</p><p>On early television sets, a dial was used to change channels. When channel surfing, the viewer was required to move the dial through each channel position, regardless of whether or not that channel had reception. On modern television sets, a next and previous button are used. When the viewer selects the “next” button, the next tuned channel will be displayed. Consider watching television in a hotel room in a strange city. When surfing through channels, the channel number is not important, but the programming is. If the programming on one channel is not of interest, the viewer can request the next channel, without knowing its number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*rEgYeu4IO93tBOCG" /></figure><pre>// A Java program to demonstrate implementation<br>// of iterator pattern with the example of<br>// notifications<br><br>// A simple Notification class<br>class Notification<br>{<br> // To store notification message<br> String notification;<br><br> public Notification(String notification)<br> {<br>  this.notification = notification;<br> }<br> public String getNotification()<br> {<br>  return notification;<br> }<br>}<br><br>// Collection interface<br>interface Collection<br>{<br> public Iterator createIterator();<br>}<br><br>// Collection of notifications<br>class NotificationCollection implements Collection<br>{<br> static final int MAX_ITEMS = 6;<br> int numberOfItems = 0;<br> Notification[] notificationList;<br><br> public NotificationCollection()<br> {<br>  notificationList = new Notification[MAX_ITEMS];<br><br>  // Let us add some dummy notifications<br>  addItem(&quot;Notification 1&quot;);<br>  addItem(&quot;Notification 2&quot;);<br>  addItem(&quot;Notification 3&quot;);<br> }<br><br> public void addItem(String str)<br> {<br>  Notification notification = new Notification(str);<br>  if (numberOfItems &gt;= MAX_ITEMS)<br>   System.err.println(&quot;Full&quot;);<br>  else<br>  {<br>   notificationList[numberOfItems] = notification;<br>   numberOfItems = numberOfItems + 1;<br>  }<br> }<br><br> public Iterator createIterator()<br> {<br>  return new NotificationIterator(notificationList);<br> }<br>}<br><br>// We could also use Java.Util.Iterator<br>interface Iterator<br>{<br> // indicates whether there are more elements to<br> // iterate over<br> boolean hasNext();<br><br> // returns the next element<br> Object next();<br>}<br><br>// Notification iterator<br>class NotificationIterator implements Iterator<br>{<br> Notification[] notificationList;<br><br> // maintains curr pos of iterator over the array<br> int pos = 0;<br><br> // Constructor takes the array of notificationList are<br> // going to iterate over.<br> public NotificationIterator (Notification[] notificationList)<br> {<br>  this.notificationList = notificationList;<br> }<br><br> public Object next()<br> {<br>  // return next element in the array and increment pos<br>  Notification notification = notificationList[pos];<br>  pos += 1;<br>  return notification;<br> }<br><br> public boolean hasNext()<br> {<br>  if (pos &gt;= notificationList.length ||<br>   notificationList[pos] == null)<br>   return false;<br>  else<br>   return true;<br> }<br>}<br><br>// Contains collection of notifications as an object of<br>// NotificationCollection<br>class NotificationBar<br>{<br> NotificationCollection notifications;<br><br> public NotificationBar(NotificationCollection notifications)<br> {<br>  this.notifications = notifications;<br> }<br><br> public void printNotifications()<br> {<br>  Iterator iterator = notifications.createIterator();<br>  System.out.println(&quot;-------NOTIFICATION BAR------------&quot;);<br>  while (iterator.hasNext())<br>  {<br>   Notification n = (Notification)iterator.next();<br>   System.out.println(n.getNotification());<br>  }<br> }<br>}<br><br>// Driver class<br>class Main<br>{<br> public static void main(String args[])<br> {<br>  NotificationCollection nc = new NotificationCollection();<br>  NotificationBar nb = new NotificationBar(nc);<br>  nb.printNotifications();<br> }<br>}</pre><pre>-------NOTIFICATION BAR------------<br>Notification 1<br>Notification 2<br>Notification 3</pre><h3>Mediator Design Pattern</h3><h4>Intent</h4><ul><li>Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.</li><li>Design an intermediary to decouple many peers.</li><li>Promote the many-to-many relationships between interacting peers to “full object status”.</li></ul><h4>Problem</h4><p>We want to design reusable components, but dependencies between the potentially reusable pieces demonstrates the “spaghetti code” phenomenon (trying to scoop a single serving results in an “all or nothing clump”).</p><h4>Discussion</h4><p>In Unix, permission to access system resources is managed at three levels of granularity: world, group, and owner. A group is a collection of users intended to model some functional affiliation. Each user on the system can be a member of one or more groups, and each group can have zero or more users assigned to it. Next figure shows three users that are assigned to all three groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*CpKefyi03j_9dx5b_7ct2g.png" /></figure><p>If we were to model this in software, we could decide to have User objects coupled to Group objects, and Group objects coupled to User objects. Then when changes occur, both classes and all their instances would be affected.</p><p>An alternate approach would be to introduce “an additional level of indirection” — take the mapping of users to groups and groups to users, and make it an abstraction unto itself. This offers several advantages: Users and Groups are decoupled from one another, many mappings can easily be maintained and manipulated simultaneously, and the mapping abstraction can be extended in the future by defining derived classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*-1SDd7Ngu6G1rDh2" /></figure><p>Partitioning a system into many objects generally enhances reusability, but proliferating interconnections between those objects tend to reduce it again. The mediator object: encapsulates all interconnections, acts as the hub of communication, is responsible for controlling and coordinating the interactions of its clients, and promotes loose coupling by keeping objects from referring to each other explicitly.</p><p>The Mediator pattern promotes a “many-to-many relationship network” to “full object status”. Modelling the inter-relationships with an object enhances encapsulation, and allows the behavior of those inter-relationships to be modified or extended through subclassing.</p><p>An example where Mediator is useful is the design of a user and group capability in an operating system. A group can have zero or more users, and, a user can be a member of zero or more groups. The Mediator pattern provides a flexible and non-invasive way to associate and manage users and groups.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*Irtgv-7GQURpU6dR" /></figure><p>Colleagues (or peers) are not coupled to one another. Each talks to the Mediator, which in turn knows and conducts the orchestration of the others. The “many to many” mapping between colleagues that would otherwise exist, has been “promoted to full object status”. This new abstraction provides a locus of indirection where additional leverage can be hosted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*GjAPZ8GLiy-lTtD_nfJw4Q.png" /></figure><h4>Example</h4><p>The Mediator defines an object that controls how a set of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower rather than explicitly communicating with one another. The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*-dt6KC-vh6si-qlEaD41JA.png" /></figure><h3>Memento Design Pattern</h3><h4>Intent</h4><ul><li>Without violating encapsulation, capture and externalize an object’s internal state so that the object can be returned to this state later.</li><li>A magic cookie that encapsulates a “check point” capability.</li><li>Promote undo or rollback to full object status.</li></ul><h4>Problem</h4><p>Need to restore an object back to its previous state (e.g. “undo” or “rollback” operations).</p><h4>Discussion</h4><p>The client requests a Memento from the source object when it needs to checkpoint the source object’s state. The source object initializes the Memento with a characterization of its state. The client is the “care-taker” of the Memento, but only the source object can store and retrieve information from the Memento (the Memento is “opaque” to the client and all other objects). If the client subsequently needs to “rollback” the source object’s state, it hands the Memento back to the source object for reinstatement.</p><p>An unlimited “undo” and “redo” capability can be readily implemented with a stack of Command objects and a stack of Memento objects.</p><p>The Memento design pattern defines three distinct roles:</p><ol><li>Originator — the object that knows how to save itself.</li><li>Caretaker — the object that knows why and when the Originator needs to save and restore itself.</li><li>Memento — the lock box that is written and read by the Originator, and shepherded by the Caretaker.</li></ol><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*FIIgpWOOt4PFr-x20OgwVA.png" /></figure><h4>Example</h4><p>The Memento captures and externalizes an object’s internal state so that the object can later be restored to that state. This pattern is common among do-it-yourself mechanics repairing drum brakes on their cars. The drums are removed from both sides, exposing both the right and left brakes. Only one side is disassembled and the other serves as a Memento of how the brake parts fit together. Only after the job has been completed on one side is the other side disassembled. When the second side is disassembled, the first side acts as the Memento.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*dH4eKHE4Mj2zMBxZ" /></figure><h3>Null Object Design Pattern</h3><h4>Intent</h4><p>The intent of a Null Object is to encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behavior. In short, a design where “nothing will come of nothing”</p><p>Use the Null Object pattern when</p><ul><li>an object requires a collaborator. The Null Object pattern does not introduce this collaboration — it makes use of a collaboration that already exists</li><li>some collaborator instances should do nothing</li><li>you want to abstract the handling of null away from the client</li></ul><h4>Problem</h4><p>Given that an object reference may be optionally null, and that the result of a null check is to do nothing or use some default value, how can the absence of an object — the presence of a null reference — be treated transparently?</p><h4>Discussion</h4><p>Sometimes a class that requires a collaborator does not need the collaborator to do anything. However, the class wishes to treat a collaborator that does nothing the same way it treats one that actually provides behavior.</p><p>Consider for example a simple screen saver which displays balls that move about the screen and have special color effects. This is easily achieved by creating a Ball class to represent the balls and using a Strategy pattern to control the ball’s motion and another Strategy pattern to control the ball’s color.</p><p>It would then be trivial to write strategies for many different types of motion and color effects and create balls with any combination of those. However, to start with you want to create the simplest strategies possible to make sure everything is working. And these strategies could also be useful later since you want as strategies as possible strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*VG22VW4QZTVZ7kEoGX-m4Q.png" /></figure><p>Now, the simplest strategy would be no strategy. That is do nothing, don’t move and don’t change color. However, the Strategy pattern requires the ball to have objects which implement the strategy interfaces. This is where the Null Object pattern becomes useful.</p><p>Simply implement a NullMovementStrategy which doesn’t move the ball and a NullColorStrategy which doesn’t change the ball’s color. Both of these can probably be implemented with essentially no code. All the methods in these classes do “nothing”. They are perfect examples of the Null Object Pattern.</p><p>The key to the Null Object pattern is an abstract class that defines the interface for all objects of this type. The Null Object is implemented as a subclass of this abstract class. Because it conforms to the abstract class’ interface, it can be used any place this type of object is needed. As compared to using a special “null” value which doesn’t actually implement the abstract interface and which must constantly be checked for with special code in any object which uses the abstract interface.</p><p>It is sometimes thought that Null Objects are over simple and “stupid” but in truth a Null Object always knows exactly what needs to be done without interacting with any other objects. So in truth it is very “smart.”</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*81ICuMUHFD4enjnnx73Dsg.png" /></figure><p>Client -</p><ul><li>requires a collaborator.</li></ul><p>AbstractObject -</p><ul><li>declares the interface for Client’s collaborator</li><li>implements default behavior for the interface common to all classes, as appropriate</li></ul><p>RealObject -</p><ul><li>defines a concrete subclass of AbstractObject whose instances provide useful behavior that Client expects</li></ul><p>NullObject -</p><ul><li>provides an interface identical to AbstractObject’s so that a null object can be substituted for a real object</li><li>implements its interface to do nothing. What exactly it means to do nothing depends on what sort of behavior Client is expecting</li><li>when there is more than one way to do nothing, more than one NullObject class may be required</li></ul><h3>Observer Design Pattern</h3><h4>Intent</h4><ul><li>Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</li><li>Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy.</li><li>The “View” part of Model-View-Controller.</li></ul><h4>Problem</h4><p>A large monolithic design does not scale well as new graphing or monitoring requirements are levied.</p><h4>Discussion</h4><p>Define an object that is the “keeper” of the data model and/or business logic (the Subject). Delegate all “view” functionality to decoupled and distinct Observer objects. Observers register themselves with the Subject as they are created. Whenever the Subject changes, it broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for that subset of the Subject’s state that it is responsible for monitoring.</p><p>This allows the number and “type” of “view” objects to be configured dynamically, instead of being statically specified at compile-time.</p><p>The protocol described above specifies a “pull” interaction model. Instead of the Subject “pushing” what has changed to all Observers, each Observer is responsible for “pulling” its particular “window of interest” from the Subject. The “push” model compromises reuse, while the “pull” model is less efficient.</p><p>Issues that are discussed, but left to the discretion of the designer, include: implementing event compression (only sending a single change broadcast after a series of consecutive changes has occurred), having a single Observer monitoring multiple Subjects, and ensuring that a Subject notify its Observers when it is about to go away.</p><p>The Observer pattern captures the lion’s share of the Model-View-Controller architecture that has been a part of the Smalltalk community for years.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*0dBTZ51n8w2ZuX8LIj3IIQ.png" /></figure><p>Subject represents the core (or independent or common or engine) abstraction. Observer represents the variable (or dependent or optional or user interface) abstraction. The Subject prompts the Observer objects to do their thing. Each Observer can call back to the Subject as needed.</p><h4>Example</h4><p>The Observer defines a one-to-many relationship so that when one object changes state, the others are notified and updated automatically. Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and “observes” when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*rnUbPFUdLVVSO5kpaO7g_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*NQML7p60iOsykkF9mVq_-w.png" /></figure><p>Below is the java implementation of this design.</p><pre>// Java implementation of above design for Cricket App. The<br>// problems with this design are discussed below.<br><br>// A class that gets information from stadium and notifies<br>// display elements, CurrentScoreDisplay &amp; AverageScoreDisplay<br>class CricketData<br>{<br> int runs, wickets;<br> float overs;<br> CurrentScoreDisplay currentScoreDisplay;<br> AverageScoreDisplay averageScoreDisplay;<br><br> // Constructor<br> public CricketData(CurrentScoreDisplay currentScoreDisplay,<br>     AverageScoreDisplay averageScoreDisplay)<br> {<br>  this.currentScoreDisplay = currentScoreDisplay;<br>  this.averageScoreDisplay = averageScoreDisplay;<br> }<br><br> // Get latest runs from stadium<br> private int getLatestRuns()<br> {<br>  // return 90 for simplicity<br>  return 90;<br> }<br><br> // Get latest wickets from stadium<br> private int getLatestWickets()<br> {<br>  // return 2 for simplicity<br>  return 2;<br> }<br><br> // Get latest overs from stadium<br> private float getLatestOvers()<br> {<br>  // return 10.2 for simplicity<br>  return (float)10.2;<br> }<br><br> // This method is used update displays when data changes<br> public void dataChanged()<br> {<br>  // get latest data<br>  runs = getLatestRuns();<br>  wickets = getLatestWickets();<br>  overs = getLatestOvers();<br><br>  currentScoreDisplay.update(runs,wickets,overs);<br>  averageScoreDisplay.update(runs,wickets,overs);<br> }<br>}<br><br>// A class to display average score. Data of this class is<br>// updated by CricketData<br>class AverageScoreDisplay<br>{<br> private float runRate;<br> private int predictedScore;<br><br> public void update(int runs, int wickets, float overs)<br> {<br>  this.runRate = (float)runs/overs;<br>  this.predictedScore = (int) (this.runRate * 50);<br>  display();<br> }<br><br> public void display()<br> {<br>  System.out.println(&quot;\nAverage Score Display:\n&quot; +<br>      &quot;Run Rate: &quot; + runRate +<br>      &quot;\nPredictedScore: &quot; + predictedScore);<br> }<br>}<br><br>// A class to display score. Data of this class is<br>// updated by CricketData<br>class CurrentScoreDisplay<br>{<br> private int runs, wickets;<br> private float overs;<br><br> public void update(int runs,int wickets,float overs)<br> {<br>  this.runs = runs;<br>  this.wickets = wickets;<br>  this.overs = overs;<br>  display();<br> }<br><br> public void display()<br> {<br>  System.out.println(&quot;\nCurrent Score Display: \n&quot; +<br>      &quot;Runs: &quot; + runs +&quot;\nWickets:&quot;<br>      + wickets + &quot;\nOvers: &quot; + overs );<br> }<br>}<br><br>// Driver class<br>class Main<br>{<br> public static void main(String args[])<br> {<br>  // Create objects for testing<br>  AverageScoreDisplay averageScoreDisplay =<br>         new AverageScoreDisplay();<br>  CurrentScoreDisplay currentScoreDisplay =<br>         new CurrentScoreDisplay();<br><br>  // Pass the displays to Cricket data<br>  CricketData cricketData = new CricketData(currentScoreDisplay,<br>            averageScoreDisplay);<br><br>  // In real app you would have some logic to call this<br>  // function when data changes<br>  cricketData.dataChanged();<br> }<br>}</pre><pre>Current Score Display: <br>Runs: 90<br>Wickets:2<br>Overs: 10.2<br><br>Average Score Display:<br>Run Rate: 8.823529<br>PredictedScore: 441</pre><h3>State Design Pattern</h3><h4>Intent</h4><ul><li>Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.</li><li>An object-oriented state machine</li><li>wrapper + polymorphic wrappee + collaboration</li></ul><h4>Problem</h4><p>A monolithic object’s behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterized by large and numerous case statements that vector flow of control based on the state of the application.</p><h4>Discussion</h4><p>The State pattern is a solution to the problem of how to make behavior depend on state.</p><ul><li>Define a “context” class to present a single interface to the outside world.</li><li>Define a State abstract base class.</li><li>Represent the different “states” of the state machine as derived classes of the State base class.</li><li>Define state-specific behavior in the appropriate State derived classes.</li><li>Maintain a pointer to the current “state” in the “context” class.</li><li>To change the state of the state machine, change the current “state” pointer</li></ul><p>The State pattern does not specify where the state transitions will be defined. The choices are two: the “context” object, or each individual State derived class. The advantage of the latter option is ease of adding new State derived classes. The disadvantage is each State derived class has knowledge of (coupling to) its siblings, which introduces dependencies between subclasses.</p><p>A table-driven approach to designing finite state machines does a good job of specifying state transitions, but it is difficult to add actions to accompany the state transitions. The pattern-based approach uses code (instead of data structures) to specify state transitions, but it does a good job of accommodating state transition actions.</p><h4>Structure</h4><p>The state machine’s interface is encapsulated in the “wrapper” class. The wrappee hierarchy’s interface mirrors the wrapper’s interface with the exception of one additional parameter. The extra parameter allows wrappee derived classes to call back to the wrapper class as necessary. Complexity that would otherwise drag down the wrapper class is neatly compartmented and encapsulated in a polymorphic hierarchy to which the wrapper object delegates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*HDcOEecy9GRpMIN2febBxA.png" /></figure><h4>Example</h4><p>The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*gNbdUoo_P3m5cgx09WTV9Q.png" /></figure><h3>Strategy Design Pattern</h3><h4>Intent</h4><ul><li>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.</li><li>Capture the abstraction in an interface, bury implementation details in derived classes.</li></ul><h4>Problem</h4><p>One of the dominant strategies of object-oriented design is the “open-closed principle”.</p><p>Figure demonstrates how this is routinely achieved — encapsulate interface details in a base class, and bury implementation details in derived classes. Clients can then couple themselves to an interface, and not have to experience the upheaval associated with change: no impact when the number of derived classes changes, and no impact when the implementation of a derived class changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*DREBv-RJQEXgKqDSKq5gwA.png" /></figure><p>A generic value of the software community for years has been, “maximize cohesion and minimize coupling”. The object-oriented design approach shown in figure is all about minimizing coupling. Since the client is coupled only to an abstraction (i.e. a useful fiction), and not a particular realization of that abstraction, the client could be said to be practicing “abstract coupling” . an object-oriented variant of the more generic exhortation “minimize coupling”.</p><p>A more popular characterization of this “abstract coupling” principle is “Program to an interface, not an implementation”.</p><p>Clients should prefer the “additional level of indirection” that an interface (or an abstract base class) affords. The interface captures the abstraction (i.e. the “useful fiction”) the client wants to exercise, and the implementations of that interface are effectively hidden.</p><h4>Structure</h4><p>The Interface entity could represent either an abstract base class, or the method signature expectations by the client. In the former case, the inheritance hierarchy represents dynamic polymorphism. In the latter case, the Interface entity represents template code in the client and the inheritance hierarchy represents static polymorphism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*Q6YFi3GMbiuSwpwFBfAx9w.png" /></figure><h4>Example</h4><p>A Strategy defines a set of algorithms that can be used interchangeably. Modes of transportation to an airport is an example of a Strategy. Several options exist such as driving one’s own car, taking a taxi, an airport shuttle, a city bus, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must choose the Strategy based on trade-offs between cost, convenience, and time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*pQwDSD_K79BOY2p08AaFEw.png" /></figure><h3>Template Method Design Pattern</h3><h4>Intent</h4><ul><li>Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.</li><li>Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.</li></ul><h4>Problem</h4><p>Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended.</p><h4>Discussion</h4><p>The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable). The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. The variant steps represent “hooks”, or “placeholders”, that can, or must, be supplied by the component’s client in a concrete derived class.</p><p>The component designer mandates the required steps of an algorithm, and the ordering of the steps, but allows the component client to extend or replace some number of these steps.</p><p>Template Method is used prominently in frameworks. Each framework implements the invariant pieces of a domain’s architecture, and defines “placeholders” for all necessary or interesting client customization options. In so doing, the framework becomes the “center of the universe”, and the client customizations are simply “the third rock from the sun”. This inverted control structure has been affectionately labelled “the Hollywood principle” — “don’t call us, we’ll call you”.</p><h4>Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*Oa0tEy41zryo84qO6FUSsg.png" /></figure><p>The implementation of template_method() is: call step_one(), call step_two(), and call step_three(). step_two() is a “hook” method — a placeholder. It is declared in the base class, and then defined in derived classes. Frameworks (large scale reuse infrastructures) use Template Method a lot. All reusable code is defined in the framework’s base classes, and then clients of the framework are free to define customizations by creating derived classes as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*64MNo_fefEYDdv82oiV7yw.png" /></figure><h4>Example</h4><p>The Template Method defines a skeleton of an algorithm in an operation, and defers some steps to subclasses. Home builders use the Template Method when developing a new subdivision. A typical subdivision consists of a limited number of floor plans with different variations available for each. Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models.</p><p>Another example: daily routine of a worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*0Vc8i4dNUU68uarZAkBs4w.png" /></figure><pre>abstract class OrderProcessTemplate<br>{<br> public boolean isGift;<br><br> public abstract void doSelect();<br><br> public abstract void doPayment();<br><br> public final void giftWrap()<br> {<br>  try<br>  {<br>   System.out.println(&quot;Gift wrap successful&quot;);<br>  }<br>  catch (Exception e)<br>  {<br>   System.out.println(&quot;Gift wrap unsuccessful&quot;);<br>  }<br> }<br><br> public abstract void doDelivery();<br><br> public final void processOrder(boolean isGift)<br> {<br>  doSelect();<br>  doPayment();<br>  if (isGift) {<br>   giftWrap();<br>  }<br>  doDelivery();<br> }<br>}<br><br><br>class NetOrder extends OrderProcessTemplate<br>{<br> @Override<br> public void doSelect()<br> {<br>  System.out.println(&quot;Item added to online shopping cart&quot;);<br>  System.out.println(&quot;Get gift wrap preference&quot;);<br>  System.out.println(&quot;Get delivery address.&quot;);<br> }<br><br> @Override<br> public void doPayment()<br> {<br>  System.out.println<br>    (&quot;Online Payment through Netbanking, card or Paytm&quot;);<br> }<br><br> @Override<br> public void doDelivery()<br> {<br>  System.out.println<br>     (&quot;Ship the item through post to delivery address&quot;);<br> }<br><br>}<br><br>class StoreOrder extends OrderProcessTemplate<br>{<br><br> @Override<br> public void doSelect()<br> {<br>  System.out.println(&quot;Customer chooses the item from shelf.&quot;);<br> }<br><br> @Override<br> public void doPayment()<br> {<br>  System.out.println(&quot;Pays at counter through cash/POS&quot;);<br> }<br><br> @Override<br> public void doDelivery()<br> {<br>  System.out.println(&quot;Item delivered to in delivery counter.&quot;);<br> }<br><br>}<br><br>class TemplateMethodPatternClient<br>{<br> public static void main(String[] args)<br> {<br>  OrderProcessTemplate netOrder = new NetOrder();<br>  netOrder.processOrder(true);<br>  System.out.println();<br>  OrderProcessTemplate storeOrder = new StoreOrder();<br>  storeOrder.processOrder(true);<br> }<br>}</pre><pre>Item added to online shopping cart<br>Get gift wrap preference<br>Get delivery address.<br>Online Payment through Netbanking, card or Paytm<br>Gift wrap successful<br>Ship the item through post to delivery address<br><br>Customer chooses the item from shelf.<br>Pays at counter through cash/POS<br>Gift wrap successful<br>Item delivered to in delivery counter.</pre><h3>Visitor Design Pattern</h3><h4>Intent</h4><ul><li>Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.</li><li>The classic technique for recovering lost type information.</li><li>Do the right thing based on the type of two objects.</li><li>Double dispatch</li></ul><h4>Problem</h4><p>Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid “polluting” the node classes with these operations. And, you don’t want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation.</p><h4>Discussion</h4><p>Visitor’s primary purpose is to abstract functionality that can be applied to an aggregate hierarchy of “element” objects. The approach encourages designing lightweight Element classes — because processing functionality is removed from their list of responsibilities. New functionality can easily be added to the original inheritance hierarchy by creating a new Visitor subclass.</p><p>Visitor implements “double dispatch”. OO messages routinely manifest “single dispatch” — the operation that is executed depends on: the name of the request, and the type of the receiver. In “double dispatch”, the operation executed depends on: the name of the request, and the type of TWO receivers (the type of the Visitor and the type of the element it visits).</p><p>The implementation proceeds as follows. Create a Visitor class hierarchy that defines a pure virtual visit() method in the abstract base class for each concrete derived class in the aggregate node hierarchy. Each visit() method accepts a single argument — a pointer or reference to an original Element derived class.</p><p>Each operation to be supported is modelled with a concrete derived class of the Visitor hierarchy. The visit() methods declared in the Visitor base class are now defined in each derived subclass by allocating the “type query and cast” code in the original implementation to the appropriate overloaded visit() method.</p><p>Add a single pure virtual accept() method to the base class of the Element hierarchy. accept() is defined to receive a single argument — a pointer or reference to the abstract base class of the Visitor hierarchy.</p><p>Each concrete derived class of the Element hierarchy implements the accept() method by simply calling the visit() method on the concrete derived instance of the Visitor hierarchy that it was passed, passing its “this” pointer as the sole argument.</p><p>Everything for “elements” and “visitors” is now set-up. When the client needs an operation to be performed, (s)he creates an instance of the Visitor object, calls the accept() method on each Element object, and passes the Visitor object.</p><p>The accept() method causes flow of control to find the correct Element subclass. Then when the visit() method is invoked, flow of control is vectored to the correct Visitor subclass. accept() dispatch plus visit() dispatch equals double dispatch.</p><p>The Visitor pattern makes adding new operations (or utilities) easy — simply add a new Visitor derived class. But, if the subclasses in the aggregate node hierarchy are not stable, keeping the Visitor subclasses in sync requires a prohibitive amount of effort.</p><p>An acknowledged objection to the Visitor pattern is that is represents a regression to functional decomposition — separate the algorithms from the data structures. While this is a legitimate interpretation, perhaps a better perspective/rationale is the goal of promoting non-traditional behavior to full object status.</p><h4>Structure</h4><p>The Element hierarchy is instrumented with a “universal method adapter”. The implementation of accept() in each Element derived class is always the same. But — it cannot be moved to the Element base class and inherited by all derived classes because a reference to this in the Element class always maps to the base type Element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*rln_7pklLCbIAc0v" /></figure><p>When the polymorphic firstDispatch() method is called on an abstract First object, the concrete type of that object is “recovered”. When the polymorphic secondDispatch() method is called on an abstract Second object, its concrete type is “recovered”. The application functionality appropriate for this pair of types can now be exercised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*MaSGnVlFBpjcOxj31ZOrfg.png" /></figure><h4>Example</h4><p>The Visitor pattern represents an operation to be performed on the elements of an object structure without changing the classes on which it operates. This pattern can be observed in the operation of a taxi company. When a person calls a taxi company (accepting a visitor), the company dispatches a cab to the customer. Upon entering the taxi the customer, or Visitor, is no longer in control of his or her own transportation, the taxi (driver) is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*fCNd15invocRqP-xfoS4oQ.png" /></figure><h3>Notes</h3><p>The November 2000 issue of JavaPro has an article by James Cooper (author of a Java companion to the GoF) on the Visitor design pattern. He suggests it “turns the tables on our object-oriented model and creates an external class to act on data in other classes … while this may seem unclean … there are good reasons for doing it.”</p><p>His primary example. Suppose you have a hierarchy of Employee-Engineer-Boss. They all enjoy a normal vacation day accrual policy, but, Bosses also participate in a “bonus” vacation day program. As a result, the interface of class Boss is different than that of class Engineer. We cannot polymorphically traverse a Composite-like organization and compute a total of the organization’s remaining vacation days. “The Visitor becomes more useful when there are several classes with different interfaces and we want to encapsulate how we get data from these classes.”</p><h4>His benefits for Visitor include:</h4><ul><li>Add functions to class libraries for which you either do not have the source or cannot change the source</li><li>Obtain data from a disparate collection of unrelated classes and use it to present the results of a global calculation to the user program</li><li>Gather related operations into a single class rather than force you to change or derive classes to add these operations</li><li>Collaborate with the Composite pattern</li></ul><p>Visitor is not good for the situation where “visited” classes are not stable. Every time a new Composite hierarchy derived class is added, every Visitor derived class must be amended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*PC1pml2MsERwl2CskxrBZQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bedd2835c29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Web Services (AWS)]]></title>
            <link>https://medium.com/@premasajan25/amazon-web-services-aws-66c2894c1489?source=rss-adfeb08545f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c2894c1489</guid>
            <dc:creator><![CDATA[Rasamanikkam Premasajan]]></dc:creator>
            <pubDate>Sat, 17 Sep 2022 04:18:56 GMT</pubDate>
            <atom:updated>2022-09-17T04:18:56.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Cloud Computing?</h3><p>Cloud computing is a term referred to storing and accessing data over the internet. It doesn’t store any data on the hard disk of your personal computer. In cloud computing, you can access data from a remote server.</p><h3>What is AWS?</h3><p>The full form of AWS is Amazon Web Services. It is a platform that offers flexible, reliable, scalable, easy-to-use and, cost-effective cloud computing solutions.</p><p>AWS is a comprehensive, easy to use computing platform offered Amazon. The platform is developed with a combination of infrastructure as a service (IaaS), platform as a service (PaaS) and packaged software as a service (SaaS) offerings.</p><h3>History of AWS</h3><ul><li>2002- AWS services launched</li><li>2006- Launched its cloud products</li><li>2012- Holds first customer event</li><li>2015- Reveals revenues achieved of $4.6 billion</li><li>2016- Surpassed $10 billon revenue target</li><li>2016- Release snowball and snowmobile</li><li>2019- Offers nearly 100 cloud services</li><li>2021- AWS comprises over 200 products and services</li></ul><h3>Important AWS Services</h3><p>Amazon Web Services offers a wide range of different business purpose global cloud-based products. The products include storage, databases, analytics, networking, mobile, development tools, enterprise applications, with a pay-as-you-go pricing model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*glqy6JHQeApz5Se0Eqb9-Q.png" /></figure><p>Here, are Cloud Compute Services offered by Amazon:</p><p>1. <strong>EC2(Elastic Compute Cloud)-</strong> EC2 is a virtual machine in the cloud on which you have OS level control. You can run this cloud server whenever you want.</p><p>2. <strong>LightSail-</strong> This cloud computing tool automatically deploys and manages the computer, storage, and networking capabilities required to run your applications.</p><p>3. <strong>Elastic Beanstalk-</strong> The tool offers automated deployment and provisioning of resources like a highly scalable production website.</p><p>4. <strong>EKS (Elastic Container Service for Kubernetes)-</strong> The tool allows you to<strong> </strong>Kubernetes on Amazon cloud environment without installation.</p><p>5. <strong>AWS Lambda-</strong> This<strong> </strong>AWS service allows you to run functions in the cloud. The tool is a big cost saver for you as you to pay only when your functions execute.</p><h3>Migration</h3><p>Migration services used to transfer data physically between your datacenter and AWS.</p><p>1. <strong>DMS (Database Migration Service)</strong>– DMS service can be used to migrate on-site databases to AWS. It helps you to migrate from one type of database to another — for example, Oracle to MySQL.</p><p>2. <strong>SMS (Server Migration Service)</strong>– SMS migration services allows you to migrate on-site servers to AWS easily and quickly.</p><p>3. <strong>Snowball</strong> — Snowball is a small application which allows you to transfer terabytes of data inside and outside of AWS environment.</p><h3>Storage</h3><p>1. <strong>Amazon Glacier-</strong> It is an extremely low-cost storage service. It offers secure and fast storage for data archiving and backup.</p><p>2. <strong>Amazon Elastic Block Store (EBS)-</strong> It provides block-level storage to use with Amazon EC2 instances. Amazon Elastic Block Store volumes are network-attached and remain independent from the life of an instance.</p><p>3. <strong>AWS Storage Gateway-</strong> This AWS service is connecting on-premises software applications with cloud-based storage. It offers secure integration between the company’s on-premises and AWS’s storage infrastructure.</p><h3>Security Services</h3><p>1. <strong>IAM (Identity and Access Management)</strong> — IAM is a secure cloud security service which helps you to manage users, assign policies, form groups to manage multiple users.</p><p>2. <strong>Inspector</strong> — It is an agent that you can install on your virtual machines, which reports any security vulnerabilities.</p><p>3. <strong>Certificate Manager</strong> — The service offers free SSL certificates for your domains that are managed by Route53.</p><p>4. <strong>WAF (Web Application Firewall)</strong> — WAF security service offers application-level protection<strong> </strong>and allows you to block SQL injection and helps you to block cross-site scripting attacks.</p><p>5. <strong>Cloud Directory</strong> — This service allows you to create flexible, cloud-native directories for managing<strong> </strong>hierarchies of data along multiple dimensions.</p><p>1. <strong>KMS (Key Management Service)</strong> — It is a managed service. This security service helps you to create and control the encryption keys<strong> </strong>which allows you to encrypt your data.</p><p>2. <strong>Organizations</strong> — You can create groups of<strong> </strong>AWS accounts using this service to manages security and automation settings.</p><p>3. <strong>Shield</strong> — Shield is managed<strong> </strong>DDoS (Distributed Denial of Service protection service). It offers safeguards against web applications running on AWS.</p><p>4. <strong>Macie</strong> — It offers a data visibility security service which helps classify and protect your sensitive critical content.</p><p>5. <strong>GuardDuty</strong> — It offers threat detection<strong> </strong>to protect your AWS accounts and workloads.</p><h3>Database Services</h3><p>1. <strong>Amazon RDS- </strong>This<strong> </strong>Database AWS service is easy to set up, operate, and scale a relational database in the cloud.</p><p>2. <strong>Amazon DynamoDB-</strong> It is a fast, fully managed NoSQL database service. It is a simple service which allow cost-effective storage and retrieval of data. It also allows you to serve any level of request traffic.</p><p>3. <strong>Amazon ElastiCache-</strong> It is a web service which makes it easy to deploy, operate, and scale an in-memory cache in the cloud.</p><p>4. <strong>Neptune- </strong>It is a fast, reliable and scalable <strong>graph database</strong> service.</p><p>5. <strong>Amazon RedShift-</strong> It is Amazon’s data warehousing solution which you can use to perform complex OLAP queries.</p><h3>Analytics</h3><p>1. <strong>Athena</strong> — This analytics service allows perm<strong> </strong>SQL queries on your S3 bucket to find files.</p><p>2. <strong>CloudSearch</strong> — You should use this AWS service to create a fully managed search engine for your website.</p><p>3. <strong>ElasticSearch</strong> — It is similar to CloudSearch. However, it offers more features like application monitoring.</p><p>4. <strong>Kinesis</strong> — This AWS analytics service helps you to stream and analyzing real-time data at massive scale.</p><p>5. <strong>QuickSight</strong> — It is a business analytics tool. It helps you to create visualizations in a dashboard for data in Amazon Web Services. For example, S3, DynamoDB, etc.</p><p>6. <strong>EMR (Elastic Map Reduce)</strong> — This AWS analytics service mainly used for big data processing like Spark, Splunk, Hadoop, etc.</p><p>7. <strong>Data Pipeline</strong> — Allows you to move data from one place to another. For example from DynamoDB to S3.</p><h3>Management Services</h3><p>1. <strong>CloudWatch</strong> — Cloud watch helps you to monitor AWS environments like EC2, RDS instances, and CPU utilization. It also triggers alarms depends on various metrics.</p><p>2. <strong>CloudFormation</strong> — It is a way of turning infrastructure into the cloud. You can use templates for providing a whole production environment in minutes.</p><p>3. <strong>CloudTrail</strong> — It offers an easy method of auditing AWS resources. It helps you to log all changes.</p><p>4. <strong>OpsWorks</strong> — The service allows you to automated Chef/Puppet deployments on AWS environment.</p><p>5. <strong>Config</strong> — This AWS service monitors your environment. The tool sends alerts about changes when you break certain defined configurations.</p><p>6. <strong>Service Catalog</strong> — This service helps large enterprises to authorize which services user will be used and which won’t.</p><p>7. <strong>AWS Auto Scaling</strong> — The service allows you to automatically scale your resources up and down based on given CloudWatch metrics.</p><p>8. <strong>Systems Manager</strong> — This AWS service allows you to group your resources. It allows you to identify issues and act on them.</p><p>9. <strong>Managed Services</strong> — It offers management of your AWS infrastructure which allows you to focus on your applications.</p><h3>Internet of Things</h3><p>1. <strong>IoT Core</strong> — It is a managed cloud AWS service. The service allows connected devices?like cars, light bulbs, sensor grids, to securely interact with cloud applications and other devices.</p><p>2. <strong>IoT Device Management</strong> — It allows you to manage your IoT devices at any scale.</p><p>3. <strong>IoT Analytics</strong> — This AWS IOT service is helpful to perform analysis on data collected by your IoT devices.</p><p>4. <strong>Amazon FreeRTOS</strong> — This real-time operating system for microcontrollers helps you to connect IoT devices in the local server or into the cloud.</p><h3>Application Services</h3><p>1. <strong>Step Functions</strong> — It is a way of visualizing what’s going inside your application and what different microservices it is using.</p><p>2. <strong>SWF (Simple Workflow Service)</strong> — The service helps you to coordinate both automated tasks and human-led tasks.</p><p>3. <strong>SNS (Simple Notification Service)</strong> — You can use this service to send you notifications in the form of email and SMS based on given AWS services.</p><p>4. <strong>SQS (Simple Queue Service)</strong> — Use this AWS service to decouple your applications. It is a pull-based service.</p><p>5. <strong>Elastic Transcoder</strong> — This AWS service tool helps you to changes a video’s format and resolution to support various devices like tablets, smartphones, and laptops of different resolutions.</p><h3>Deployment and Management</h3><p>1. <strong>AWS CloudTrail: </strong>The services records AWS API calls and send backlog files to you.</p><p>2. <strong>Amazon CloudWatch:</strong> The tools monitor AWS resources like Amazon EC2 and Amazon RDS DB Instances. It also allows you to monitor custom metrics created by user’s applications and services.</p><p>3. <strong>AWS CloudHSM: </strong>This AWS service helps you meet corporate, regulatory, and contractual, compliance requirements for maintaining data security by using the Hardware Security Module(HSM) appliances inside the AWS environment.</p><h3>Developer Tools</h3><p>1. <strong>CodeStar</strong> — Codestar is a cloud-based service for creating, managing, and working with various software development projects on AWS.</p><p>2. <strong>CodeCommit</strong> — It is AWS’s version control service<strong> </strong>which allows you to<strong> </strong>store your code and other assets privately in the cloud.</p><p>3. <strong>CodeBuild</strong> — This Amazon developer service help you to automates the process of building and compiling<strong> </strong>your code.</p><p>4. <strong>CodeDeploy</strong> — It is a way of deploying your code in EC2 instances automatically.</p><p>5. <strong>CodePipeline</strong> — It helps you create a deployment pipeline like testing, building, testing, authentication, deployment on development and production environments.</p><p>6. <strong>Cloud9</strong> — It is an Integrated Development Environment for writing, running, and debugging code in the cloud.</p><h3>Mobile Services</h3><p>1. <strong>Mobile Hub</strong> — Allows you to add, configure and design features for mobile apps.</p><p>2. <strong>Cognito</strong> — Allows users to signup using his or her social identity.</p><p>3. <strong>Device Farm</strong> — Device farm helps you to improve the quality of apps by quickly testing hundreds of mobile devices.</p><p>4. <strong>AWS AppSync</strong> — It is a fully managed GraphQL service that offers real-time data synchronization and offline programming features.</p><h3>Business Productivity</h3><p>1. <strong>Alexa for Business</strong> — It empowers your organization with voice, using Alexa. It will help you to Allows you to build custom voice skills for your organization.</p><p>2. <strong>Chime</strong> — Can be used for online meeting and video conferencing.</p><p>3. <strong>WorkDocs</strong> — Helps to store documents in the cloud</p><p>4. <strong>WorkMail</strong> — Allows you to send and receive business emails.</p><h3>Desktop &amp; App Streaming</h3><p>1. <strong>WorkSpaces</strong> — Workspace is a VDI<strong> </strong>(Virtual Desktop Infrastructure). It allows you to use remote desktops in the cloud.</p><p>2. <strong>AppStream — </strong>A way of<strong> </strong>streaming desktop applications<strong> </strong>to your users in the web browser. For example, using MS Word in Google Chrome.</p><h3>Artificial Intelligence</h3><p>1. <strong>Lex</strong> — Lex tool helps you to build chatbots<strong> quickly.</strong></p><p>2. <strong>Polly</strong> — It is AWS’s text-to-speech service allows you to create audio versions of your notes.</p><p>3. <strong>Rekognition </strong>— It is AWS’s face recognition service. This AWS service helps you to recognize faces and object in images and videos.</p><p>4. <strong>SageMaker</strong> — Sagemaker allows you to build, train, and deploy machine learning models at any scale.</p><p>5. <strong>Transcribe</strong> — It is AWS’s speech-to-text service that offers high-quality and affordable transcriptions.</p><p>6. <strong>Translate</strong> — It is a very similar tool to Google Translate which allows you to translate text in one language to another.</p><h3>AR &amp; VR (Augmented Reality &amp; Virtual Reality)</h3><p>1. <strong>Sumerian</strong> — Sumerian is a set of tool for offering high-quality virtual reality (VR) experiences on the web. The service allows you to create interactive 3D scenes and publish it as a website for users to access.</p><h3>Customer Engagement</h3><p>1. <strong>Amazon Connect</strong> — Amazon Connect allows you to create your customer care center<strong> </strong>in the cloud.</p><p>2. <strong>Pinpoint</strong> — Pinpoint helps you to understand your users and engage with them.</p><p>3. <strong>SES (Simple Email Service)</strong> — Helps you to send bulk<strong> </strong>emails to your customers at a relatively cost-effective price.</p><h3>Game Development</h3><p>1. <strong>GameLift</strong>– It is a service which is managed by AWS. You can use this service to host dedicated game servers. It allows you to scale seamlessly without taking your game offline.</p><h3>Applications of AWS services</h3><p>Amazon Web services are widely used for various computing purposes like:</p><ul><li>Web site hosting</li><li>Application hosting/SaaS hosting</li><li>Media Sharing (Image/ Video)</li><li>Mobile and Social Applications</li><li>Content delivery and Media Distribution</li><li>Storage, backup, and disaster recovery</li><li>Development and test environments</li><li>Academic Computing</li><li>Search Engines</li><li>Social Networking</li></ul><h3>Companies using AWS</h3><ul><li>Instagram</li><li>Netflix</li><li>Twitch</li><li>LinkedIn</li><li>Facebook</li><li>Turner Broadcasting: $10 million</li><li>Zoopla</li><li>Smugmug</li><li>Pinterest</li><li>Dropbox</li></ul><h3>Advantages of AWS</h3><p>Following are the pros of using AWS services:</p><ul><li>AWS allows organizations to use the already familiar programming models, operating systems, databases, and architectures.</li><li>It is a cost-effective service that allows you to pay only for what you use, without any up-front or long-term commitments.</li><li>You will not require to spend money on running and maintaining data centers.</li><li>Offers fast deployments</li><li>You can easily add or remove capacity.</li><li>You are allowed cloud access quickly with limitless capacity.</li><li>Total Cost of Ownership is very low compared to any private/dedicated servers.</li><li>Offers Centralized Billing and management</li><li>Offers Hybrid Capabilities</li><li>Allows you to deploy your application in multiple regions around the world with just a few clicks</li></ul><h3>Disadvantages of AWS</h3><ul><li>If you need more immediate or intensive assistance, you’ll have to opt for paid support packages.</li><li>Amazon Web Services may have some common cloud computing issues when you move to a cloud. For example, downtime, limited control, and backup protection.</li><li>AWS sets default limits on resources which differ from region to region. These resources consist of images, volumes, and snapshots.</li><li>Hardware-level changes happen to your application which may not offer the best performance and usage of your applications.</li></ul><p>-THANK YOU-</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c2894c1489" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Keys in DBMS?]]></title>
            <link>https://medium.com/@premasajan25/what-are-keys-in-dbms-e2998f60b5d7?source=rss-adfeb08545f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2998f60b5d7</guid>
            <dc:creator><![CDATA[Rasamanikkam Premasajan]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 17:00:05 GMT</pubDate>
            <atom:updated>2022-09-02T17:00:05.419Z</atom:updated>
            <content:encoded><![CDATA[<p>KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple) in a relation(table). They allow you to find the relation between two tables. Keys help you uniquely identify a row in a table by a combination of one or more columns in that table. Key is also helpful for finding unique record or row from the table. Database key is also helpful for finding unique record or row from the table.</p><p>What are Keys in DBMS?</p><p>KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple) in a relation(table). They allow you to find the relation between two tables. Keys help you uniquely identify a row in a table by a combination of one or more columns in that table. Key is also helpful for finding unique record or row from the table. Database key is also helpful for finding unique record or row from the table.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*jBJ8Vb6L51BFk87nE670oQ.png" /></figure><p>In the above-given example, employee ID is a primary key because it uniquely identifies an employee record. In this table, no other employee can have the same employee ID.</p><h3>Why we need a Key?</h3><p>Here are some reasons for using sql key in the DBMS system.</p><ul><li>Keys help you to identify any row of data in a table. In a real-world application, a table could contain thousands of records. Moreover, the records could be duplicated. Keys in RDBMS ensure that you can uniquely identify a table record despite these challenges.</li><li>Allows you to establish a relationship between and identify the relation between tables</li><li>Help you to enforce identity and integrity in the relationship.</li></ul><h3>Types of Keys in DBMS (Database Management System)</h3><p>There are mainly Eight different types of Keys in DBMS and each key has it’s different functionality:</p><p>1. Super Key</p><p>2. Primary Key</p><p>3. Candidate Key</p><p>4. Alternate Key</p><p>5. Foreign Key</p><p>6. Compound Key</p><p>7. Composite Key</p><p>8. Surrogate Key</p><p>Let’s look at each of the keys in DBMS with example:</p><ul><li>Super Key — A super key is a group of single or multiple keys which identifies rows in a table.</li><li>Primary Key — is a column or group of columns in a table that uniquely identify every row in that table.</li><li>Candidate Key — is a set of attributes that uniquely identify tuples in a table. Candidate Key is a super key with no repeated attributes.</li><li>Alternate Key — is a column or group of columns in a table that uniquely identify every row in that table.</li><li>Foreign Key — is a column that creates a relationship between two tables. The purpose of Foreign keys is to maintain data integrity and allow navigation between two different instances of an entity.</li><li>Compound Key — has two or more attributes that allow you to uniquely recognize a specific record. It is possible that each column may not be unique by itself within the database.</li><li>Composite Key — is a combination of two or more columns that uniquely identify rows in a table. The combination of columns guarantees uniqueness, though individual uniqueness is not guaranteed.</li><li>Surrogate Key — An artificial key which aims to uniquely identify each record is called a surrogate key. These kind of key are unique because they are created when you don’t have any natural primary key.</li></ul><p>A superkey is a group of single or multiple keys which identifies rows in a table. A Super key may have additional attributes that are not needed for unique identification.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*Fqo2HNLpl9F-7XhxhCOyTA.png" /></figure><p>In the above-given example, EmpSSN and EmpNum name are superkeys.</p><h3>What is a Primary Key?</h3><p>PRIMARY KEY in <a href="https://www.guru99.com/dbms-tutorial.html">DBMS</a> is a column or group of columns in a table that uniquely identify every row in that table. The Primary Key can’t be a duplicate meaning the same value can’t appear more than once in the table. A table cannot have more than one primary key.</p><h3>Rules for defining Primary key:</h3><ul><li>Two rows can’t have the same primary key value</li><li>It must for every row to have a primary key value.</li><li>The primary key field cannot be null.</li><li>The value in a primary key column can never be modified or updated if any foreign key refers to that primary key.</li></ul><p>Example:</p><p>In the following example, &lt;code&gt;StudID&lt;/code&gt; is a Primary Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*sNB89ESTT1hEto43Y3niVw.png" /></figure><h3>What is the Alternate key?</h3><p>ALTERNATE KEYS is a column or group of columns in a table that uniquely identify every row in that table. A table can have multiple choices for a primary key but only one can be set as the primary key. All the keys which are not primary key are called an Alternate Key.</p><p>Example:</p><p>In this table, StudID, Roll No, Email are qualified to become a primary key. But since StudID is the primary key, Roll No, Email becomes the alternative key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*zGrG7t4FN3G4XAUudKyL2Q.png" /></figure><h3>What is a Candidate Key?</h3><p>CANDIDATE KEY in SQL is a set of attributes that uniquely identify tuples in a table. Candidate Key is a super key with no repeated attributes. The Primary key should be selected from the candidate keys. Every table must have at least a single candidate key. A table can have multiple candidate keys but only a single primary key.</p><p>Properties of Candidate key:</p><ul><li>It must contain unique values</li><li>Candidate key in SQL may have multiple attributes</li><li>Must not contain null values</li><li>It should contain minimum fields to ensure uniqueness</li><li>Uniquely identify each record in a table</li></ul><p>Candidate key Example: In the given table Stud ID, Roll No, and email are candidate keys which help us to uniquely identify the student record in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*MVJY7Yxpl8Izhz0LfpmCVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*L7hEpTd8W5zUy0VJLnqibA.png" /><figcaption>Candidate Key in DBMS</figcaption></figure><h3>What is the Foreign key?</h3><p>FOREIGN KEY is a column that creates a relationship between two tables. The purpose of Foreign keys is to maintain data integrity and allow navigation between two different instances of an entity. It acts as a cross-reference between two tables as it references the primary key of another table.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*OC1nGGbHNL3-7mA2ZPEQvA.png" /></figure><p>In this table, adding the foreign key in Deptcode to the Teacher name, we can create a relationship between the two tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*QbRlKsto8GBKYziUaVcj1Q.png" /></figure><p>This concept is also known as Referential Integrity.</p><p>COMPOUND KEY has two or more attributes that allow you to uniquely recognize a specific record. It is possible that each column may not be unique by itself within the database. However, when combined with the other column or columns the combination of composite keys become unique. The purpose of the compound key in database is to uniquely identify each record in the table.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*78UaQ_gJRHySEtP-6-_VGg.png" /></figure><p>In this example, OrderNo and ProductID can’t be a primary key as it does not uniquely identify a record. However, a compound key of Order ID and Product ID could be used as it uniquely identified each record.</p><h3>What is the Composite key?</h3><p>COMPOSITE KEY is a combination of two or more columns that uniquely identify rows in a table. The combination of columns guarantees uniqueness, though individually uniqueness is not guaranteed. Hence, they are combined to uniquely identify records in a table.</p><p>The difference between compound and the composite key is that any part of the compound key can be a foreign key, but the composite key may or maybe not a part of the foreign key.</p><h3>What is a Surrogate key?</h3><p>SURROGATE KEYS is An artificial key which aims to uniquely identify each record is called a surrogate key. This kind of partial key in dbms is unique because it is created when you don’t have any natural primary key. They do not lend any meaning to the data in the table. Surrogate key in DBMS is usually an integer. A surrogate key is a value generated right before the record is inserted into a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*qhus-p99ZG4RFuiqe6e2rA.png" /></figure><p>Above, given example, shown shift timings of the different employee. In this example, a surrogate key is needed to uniquely identify each employee.</p><p>Surrogate keys in sql are allowed when</p><ul><li>No property has the parameter of the primary key.</li><li>In the table when the primary key is too big or complicated.</li></ul><h3>Difference Between Primary key &amp; Foreign key</h3><p>Following is the main difference between primary key and foreign key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*btrpEOhkRsj-hVl6t6dyDA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2998f60b5d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s learn about File system Vs DBMS]]></title>
            <link>https://medium.com/@premasajan25/lets-learn-about-file-system-vs-dbms-b2b38cc8062f?source=rss-adfeb08545f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2b38cc8062f</guid>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[dbms]]></category>
            <dc:creator><![CDATA[Rasamanikkam Premasajan]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 16:14:27 GMT</pubDate>
            <atom:updated>2022-07-11T06:58:27.034Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Introduction</em></strong></blockquote><p>You must have used a conventional file processing system a lot of times. Yeah, it makes our lives easier by organizing our files. But, do you ever wonder, what if we could add a ton of extra features to it, making it much more efficient in terms of accessibility and a more systematic way of performing operations on your data? That’s exactly what Database Management System or a DBMS does!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*lJreN06KkrNbNYLKEccdwA.png" /></figure><p><strong><em>File System Approach</em></strong></p><p>File based systems were an early attempt to computerize the manual system. It is also called a traditional based approach in which a decentralized approach was taken where each department stored and controlled its own data with the help of a data processing specialist. The main role of a data processing specialist was to create the necessary computer file structures, and also manage the data within structures and design some application programs that create reports based on file data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*zideO646ImRllby8uTd0qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*FG-Cr8N5EjlCCZMI90Q8aw.png" /></figure><p><strong><em>In the above figure:</em></strong></p><p>Consider an example of a student’s file system. The student file will contain information regarding the student (i.e. roll no, student name, course etc.). Similarly, we have a subject file that contains information about the subject and the result file which contains the information regarding the result.</p><p>Some fields are duplicated in more than one file, which leads to data redundancy. So to overcome this problem, we need to create a centralized system, i.e. DBMS</p><p><strong>DBMS:</strong></p><p>A database approach is a well-organized collection of data that are related in a meaningful way which can be accessed by different users but stored only once in a system. The various operations performed by the DBMS system are: Insertion, deletion, selection, sorting etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*UfzFvFx4k3tguf6O-fXgyg.png" /></figure><p><strong>In the above figure,</strong></p><p>In the above figure, duplication of data is reduced due to centralization of data</p><p><strong>Difference between File System and DBMS</strong></p><p>Here, we will first differentiate a file processing system and database management system in terms of certain aspects, and later we will summarise them in a tabular form. Without waiting anymore, let’s begin:</p><p><strong>1. Data Redundancy and Consistency</strong></p><p>In an FPS, files are created in different formats and in different programming languages. Also, they are also duplicated at times, leading to redundancy of data, which in turn leads to occupying of more storage.</p><p>Whereas DBMS controls redundancy, as one item is stored at only one place in a DBMS, so there is no redundancy or inconsistency, and in addition to that, this saves a lot of storage space!</p><p><strong>2. Ease of Accessing Data</strong></p><p>In an FPS, we can access data using 2 methods, either manually or by means of an application program.</p><p><strong>Example:</strong> If we want to generate a list of customers in a bank with pincode 201002, result of both methods would be unsatisfactory, i.e., file processing systems don’t allow needed data to be retrieved in a convenient and efficient manner.</p><p>On the other hand, DBMS uses queries, which obviously provide an easy route to search for the required data. Moreover, they represent complex relationships among data easily, using the concept of foreign keys. Now, if we were to look for the bank customer records in a DBMS, it would be very easy, and could be done in just a single SQL query!</p><p>In the above query, ‘Database’ is the name of the bank database in which the details of the customers are stored, and cust_pincode is the name of the column or attribute in which pincodes of the customers are stored.</p><p><strong>3. Data Integrity</strong></p><p>In the case of FPS, data is scattered in files, which may be in different formats which makes it pretty difficult to write programs to retrieve appropriate data. Whereas DBMS enforces integrity constraints, which means it enforces and provides capabilities for defining constraints that must hold for data, or in other words, to specify the data type for each data item!</p><p><strong>4. Atomicity</strong></p><p>A computer system, at times is subject to failure.</p><p><strong>Example:</strong> If a system fails, it is possible that money may be debited from the sender’s account and not received by the receiver. Therefore, you can see how this would cause an inconsistent state of transactions.</p><p>DBMS solves this problem by following the atomicity property, which means that a transaction or operation should either be fully complete, or should not start at all!</p><p><strong>5. Concurrent Access</strong></p><p>When multiple users update data simultaneously, the concurrent updates may result in inconsistent data.</p><p><strong>Example:</strong> Two customers withdraw funds of Rs. 100 and Rs. 50 from a joint account with a balance of Rs. 500. Then, the account may contain Rs. 400 or Rs. 450 depending on who does the last transaction, rather than the actual current amount, i.e., Rs. 350.</p><p>And on the other hand, DBMS has concurrency control mechanism. Concurrency control regulates the number of people who can access a database at the same time. It keeps data centralized and prohibits two people from altering the same record at the same time.</p><p><strong>6. Security of Data</strong></p><p>We do not want all users to be able to access all data. But in file processing system, application programs are added in ad-hoc manner, and enforcing such security constraints is difficult.</p><p>Whereas, DBMS provides security and authorization subsystem, which ensures that some users are not authorized to access all the data in the database.</p><p><strong>7. Backup and Recovery</strong></p><p>Sometimes, data is lost. This could happen due to software failures or other reasons. A file processing system is not immune to such problems.</p><p>The same thing could happen in DBMS, but it does provide users the facilities of backup and recovery of data so that the valuable data isn’t lost.</p><p><strong>8. Data Independence</strong></p><p>A file processing system doesn’t provide data independence, while on the other hand, DBMS provides two kinds of data independence, physical and logical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*2GNbjOgt1lb1vR5O3fJ6eA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2b38cc8062f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>