------*%*%##$@$##%*%*----*%*%##$@$##%*%*----*%*%##$@$##%*%*----*%*%##$@$##%*%*------
Thuốc để giải ưu phiền là công việc, thú vui chỉ là liệu thuốc tạm thời..
---------------------------------------------------------------------------------------------------------------
Ever wondered how large enterprise scale systems are designed? Before major software development starts, we have to choose a suitable architecture that will provide us with the desired functionality and quality attributes. Hence, we should understand different architectures, before applying them to our design.
What is an Architectural Pattern?
According to Wikipedia,
An architectural pattern is a general, reusable solution to a commonly occurring problem in software architecture within a given context. Architectural patterns are similar to software design pattern but have a broader scope.
In this article, I will be briefly explaining the following 10 common architectural patterns with their usage, pros and cons.
Layered pattern
Client-server pattern
Master-slave pattern
Pipe-filter pattern
Broker pattern
Peer-to-peer pattern
Event-bus pattern
Model-view-controller pattern
Blackboard pattern
Interpreter pattern
1. Layered pattern
This pattern is also known as n-tier architecturepattern. It can be used to structure programs that can be decomposed into groups of subtasks, each of which is at a particular level of abstraction. Each layer provides services to the next higher layer.
The most commonly found 4 layers of a general information system are as follows.
Presentation layer (also known as UI layer)
Application layer (also known as service layer)
Business logic layer (also known as domain layer)
Data access layer (also known as persistence layer)
Usage
General desktop applications.
E commerce web applications.
Layered pattern
2. Client-server pattern
This pattern consists of two parties; a server and multiple clients. The server component will provide services to multiple client components. Clients request services from the server and the server provides relevant services to those clients. Furthermore, the server continues to listen to client requests.
Usage
Online applications such as email, document sharing and banking.
Client-server pattern
3. Master-slave pattern
This pattern consists of two parties; master and slaves. The master component distributes the work among identical slave components, and computes a final result from the results which the slaves return.
Usage
In database replication, the master database is regarded as the authoritative source, and the slave databases are synchronized to it.
Peripherals connected to a bus in a computer system (master and slave drives).
Master-slave pattern
4. Pipe-filter pattern
This pattern can be used to structure systems which produce and process a stream of data. Each processing step is enclosed within a filter component. Data to be processed is passed through pipes. These pipes can be used for buffering or for synchronization purposes.
Usage
Compilers. The consecutive filters perform lexical analysis, parsing, semantic analysis, and code generation.
Workflows in bioinformatics.
Pipe-filter pattern
5. Broker pattern
This pattern is used to structure distributed systems with decoupled components. These components can interact with each other by remote service invocations. A broker component is responsible for the coordination of communication among components.
Servers publish their capabilities (services and characteristics) to a broker. Clients request a service from the broker, and the broker then redirects the client to a suitable service from its registry.
In this pattern, individual components are known as peers. Peers may function both as a client, requesting services from other peers, and as a server, providing services to other peers. A peer may act as a client or as a server or as both, and it can change its role dynamically with time.
Proprietary multimedia applications such as Spotify.
Peer-to-peer pattern
7. Event-bus pattern
This pattern is a primarily deals with events and has 4 major components; event source, event listener, channel and event bus. Sources publish messages to particular channels on an event bus. Listeners subscribe to particular channels. Listeners are notified of messages that are published to a channel to which they have subscribed before.
Usage
Android development
Notification services
Event-bus pattern
8. Model-view-controller pattern
This pattern, also known as MVC pattern, divides an interactive application in to 3 parts as,
model — contains the core functionality and data
view — displays the information to the user (more than one view may be defined)
controller — handles the input from the user
This is done to separate internal representations of information from the ways information is presented to, and accepted from, the user. It decouples components and allows efficient code reuse.
Usage
Architecture for World Wide Web applications in major programming languages.
This pattern is useful for problems for which no deterministic solution strategies are known. The blackboard pattern consists of 3 main components.
blackboard — a structured global memory containing objects from the solution space
knowledge source — specialized modules with their own representation
control component — selects, configures and executes modules.
All the components have access to the blackboard. Components may produce new data objects that are added to the blackboard. Components look for particular kinds of data on the blackboard, and may find these by pattern matching with the existing knowledge source.
Usage
Speech recognition
Vehicle identification and tracking
Protein structure identification
Sonar signals interpretation.
Blackboard pattern
10. Interpreter pattern
This pattern is used for designing a component that interprets programs written in a dedicated language. It mainly specifies how to evaluate lines of programs, known as sentences or expressions written in a particular language. The basic idea is to have a class for each symbol of the language.
Usage
Database query languages such as SQL.
Languages used to describe communication protocols.
Interpreter pattern
Comparison of Architectural Patterns
The table given below summarizes the pros and cons of each architectural pattern. Click on the cell to view the full text within.
Comparison of Architectural Patterns
Hope you found this article useful. I would love to hear your thoughts. 😇
We are going to deploy a GitHub repo to Azure App Service and configure CI/CD for that repo through the Azure CLI 2.0 so if you’re not aware of the Azure CLI 2.0, I will request you to go to my previous blog posts here and here.
First, we will list down all the steps required for it. The steps are as follows:
Create a Resource Group
We will create a resource group with the name githubdemorg and host it in location EASTUS
az group create –name githubdemoorg –location EASTUS Create an App Service Plan
An App Service Plan is to define the size, location, scale count, and sku of the app where you will be hosting it.
az appservice plan create –name githubdemplan –resource-group githubdemoorg –sku FREE Create a Web App
We will create a new web app with the following command.
az appservice web create –name githubdemoag –resource-group githubdemorg –plan githubdemoplan Create a Git repo in Github
If you’re not familiar with github, just follow the steps.
Go to Github.com and Signup/login with your Credentials
Click on Start a project
Create a new repository by passing a repo name and description and make your Repo as public. Also, make sure that you didn’t check the Initialize this repository with a README if you’re not familiar with github and blindly follow this demo.
Push the Code to the Github
Go to your code directory and open a new instance of the command prompt for the git command and follow the new or existing repository on the command line according to the requirement.
For us, we did the new repository in the demo. Let me quickly walk through the commands.
git init
It’s going to initiate a new blank repository in your local
git add readme.md
It is going to add a readme file to the repo.
git commit –m “first commit”
It is going to commit the code with the message in the double quote
git remote add origin url
It’s going to add the remote to the origin.
git push –u origin master
It’s going to push to origin git repo in the master branch
Once you completed the above commands then go to your repo on github and check if the files got pushed.
Deploy Code from a public Github Repository with CI &CD
In order to set up the source control config, you need to authenticate your command line with a token, and in order to get the token you need to go to github.com and then settings and on bottom left click on personal access token.
Click on "Generate new token" and enter the token description.
Click on "Generate token" button at the bottom.
Copy the token generated in this step and use it in the next step. I have not used it in the screenshot below as I have already set up the token once and Azure remembers the token.
az appservice web source-control config –name githubdemoag –resource-group githubdemorg –repo-url YOURREPOURL –branch master --git-token $token Validate CI & CD
Now, to validate the CI CD Configuration, I am going to make a simple code change in my HTML and append Updated to GITHUB DEMO and I am going to push the code to git hub and check the site again to see if the changes are reflecting or not.
Update the HTML File
Push the code to the github by using the following commands in your git cmd
Audience for this topic - Developers and Application Architects.
What will you learn from the topic
I know you already familiar with Dependency Inversion(DI) and Inversion of Control (IOC). So, if you already know this, but you are not confident enough to inject dependency into your components; but you want to reuse your componets and want to know best design practice for the components then this article is for you. If you prefer Layers style, N-Tier architecture style, Onion or Daisy architecture style using and Domain-Driven-Design or some others then you may need different implementations of the same type of the components for the same or different applications. So, first know about the dependency, their types and characteristics then injecting the dependency will be very easy and you will be ready to use Dependency-Inversion principle.
Anyway, the following concepts will be covered in this topic -
What is Dependency
Type of Dependency
Characteristics of the Dependency
Use of the dependency in your class design
Dependency Inversion
In what Scenarios force to use DI
What is DI and IOC
Type of DI
Advantages and disadvantages of DI
IOC Framework
Use of Munq to your Web application
Use of Managed Extensibility Framework (MEF)
Let's Drilldown the Basic Concept In DI
No more theory and definition, let's see the example
In the example,
Customer Class needs classes 'CheckingAccount' and 'SavingAccount' classes to do its work.
"Customer" Class can't do its work without classes 'CheckingAccount' and 'SavingAccount'.
Therefore,
"Customer" Class is a dependent of classes 'CheckingAccount' and 'SavingAccount'.
Classes 'CheckingAccount' and 'SavingAccount' are dependency of class "Customer"
Class Relations of Dependency
Two classes (Customer and IBankAccount) that use each other are called "coupled".
The coupling between classes can be loose or tight or somewhere in between.
Tight Coupling Dependencies
In the example CheckingAccount and SavingingAccount are tightly coupled with the customer class. This implementation violates the Opened-Closed principles where your classes should be open for extension but closed for modifications. Anyway, forget the principle. Just think that your checking-account class is fixed in this design and if you need another implantation of the checking-account class then what should you do?
Loose Coupling Dependencies
In the example, the implementation of the interface IBankAccount are CheckingAccount and SavingingAccount which are loosely coupled in the customer class. You can inject any different implementation of the IBankAccount into the Customer class.
Direction of Dependency
Dependencies or couplings are directional.
The Customer depends on IBankAccount which doesn't mean that IBankAccount also depends on Customer.
Characteristics of Dependency
Visible Dependencies
Hidden Dependencies
Direct Dependencies
Indirect Dependencies
Compile-Time Dependencies
Run-Time Dependency
Visible Dependencies
In the example the implementation of the interface IBankAccount are CheckingAccount and SavingingAccount. If you want to create an instance of a customer class then you can inject any different implementation of the IBankAccount using its constructor. It is visible during object creation.
Hidden Dependency
Now if you create an object of the Customer class then you will not get any chance to inject any of the implementation of the IBankAccount Interface. It is hidden during object creation.
Direct Dependency
In this example, Customer class uses IBankAccount. It means Customer has a direct dependency on IBankAccount. So, it is called direct dependency.
Indirect Dependency
In the example CheckingAccount Class has a direct dependency with DataAccessForChecking.
So, Customer has a direct dependency with CheckingAccount. Again Checking Account has a direct dependency with DataAccessForChecking. So, Customer lass has an indirect dependency with DataAccessForChecking.
To keep it simple, right now I'm avoiding the compile-Time and run-time dependency. Later I will explain when I will discuss MEF and MUNQ Section.
Finally I can say that change the way you think then you will realize the fact.
Dependency Inversion
Look at the above example where we are considering a layer architecture. I am taking this architecture as an example. Note that Tier and Layer are two different style. I am ignoring that part as my main goal to show you the DI and IOC.
The Presentation Layer(PL) which may contain User Interface Layer(UI) and Presentation Logic Layer(PLL).To make it easy say we have a web application and the UI means the web-form like *.aspx for ASP.NET or the view like *.cshtml for ASP.NET MVC. PLL means the controller class for the ASP.NET MVC or the *.aspx.cs for ASP.NET.
Business Layer (BL) could be you domain layer. The Data Access Layer (DAL). You can use any ORM like Entity-Frame-work as a DAL.
Say, you have bought some products using any web portal. Now you want to see your order items. So, when you click on a button to display your order then View will communicate with the controller class. Controller class will call the BL and then BL will call the DAL to verify the customer account information and then finally DAL will send the order information to the BL and BL send it to the PL to display the order list.
In a short, the layers work as follows -
PL depends on BL
BL depends on DAL
So, high level layer depends on the low level layers and these are tight coupling layers. We can't change this dependency at the run time or if we have more than one implementations of the DAL or BLL then what happen? Can we able to change the way of the dependency from the layers?
Real Life Scenario
Just for easy understanding let's say, you have different implementation of the DLL. For example, IDataAccess has two implementations and these are DataAccessForSql and DataAccessForOracle. Depending on the customers sometimes you need DataAccessForSql and sometimes you need DataAccessForOracle. But tight coupling design will not help you in this scenarios.
Again you have more than one payment system like PayPal, Visa and MasterCard. You need different implementation of your business logics depending on the payment system. For example, say, IPayment has some implementation like PaymentForMasterCard, PaymentForPayPal and PaymentForVisa. So, you need to switch from one to another depend on the preference of the customer. Tight coupling design will not give you this facilities.
So, solution is the Dependency Inversion.
Principle of the Dependency Inversion
It states that "High-level layers should not depend on low-level layers. Both should depend on abstractions".
So, we can inject any of the implementation of the DAL to the BL and any of the implementation of BL to the PL.
Dependency Injection
Dependency injection is a style of object configuration in which objects are configured by an external entity.
In What Scenarios Do You Need DI
Never use DI unless - you don't have the control over the lifecycle of the objects.
Don't use Container unless something forces you to do that.
If you have control to call new to create an object then never need DI container.
Constructor Injection
Constructor injection uses parameter to inject dependencies.
Setter Injection
Use setter method to inject the object's dependencies.
Interface injection
Interface injection is used when an object is defined by an interface and it must be implemented in order to inject dependencies at runtime. So, design an interface to inject dependencies.
Disadvantage of DI
The guessing that you have decoupled by implementing DI without decoupling it. This is the worse part about DI.
Advantage of DI
Unit Test or testable code
Reuseable code
DI helps you with SR (Single Responsibility) and SoC (Separation of Concerns).
DI is not effective if
You will never need a
Different implementation.
Different configuration.
Dependency injection is effective If
You need to inject,
Different implementations of the same dependency.
The same dependency into multiple components.
Configuration data into multiple components.
The same implementation in different configurations.
Inversion of Control (IoC)
IoC refers to the containers. It is an implementation of using DI which refers to the actual pattern. IoC containers are useful with static dependencies which is used at compile-time and MEF is useful with dynamic dependencies which is used only at run-time.
List of .NET IOC Framework
Unity
Managed Extensibility Framework(MEF)
Munq
Funq
LightCore
Spring .NET
Castle Windsor
Autofac
Structure Map
Puzzle.NFactory
Ninject
S2Container.NET
Winter4Net
Which Dependency Injection Tool Should You Use
Munq is good for web
Unity is good for Enterprise
IOC container is best if you want to implement the entire application.
If you want to extend only and it is developed by 3rd-party then MEF could be the best.
Ninject is too slow container.
Note that there is some philosophical contradiction. But my main goal is to give you an idea so that, you can capture it easily. These are not hard coded rules; so if you have different opinions then you are right too.
copy from http://www.c-sharpcorner.com/article/first-know-about-the-dependency-before-di/