目录

· 概述

· Factory

· What is the Factory Design Pattern?

· Sample Code

· Abstract Factory

· What is the Abstract Factory Design Pattern?

· What can you do with an Abstract Factory Design Pattern?

· Sample Code

· Singleton

· What is the Singleton Design Pattern?

· Sample Code

· Builder

· What is the Builder Design Pattern?

· Sample Code

· Prototype

· What is the Prototype Design Pattern?

· Sample Code


概述

最近在YouTube上看了一套不错的设计模式视频,同时翻看GOF的《设计模式 可复用面向对象软件的基础》,刷新了我对设计模式的认识。加之之前的一篇博文《设计模式笔记——GoF设计模式汇总》中未提及比较少用的解释器和访问者模式,以及大陆无法打开YouTube等原因,所以将这套视频所学到的主要内容记录成笔记,供未来需要时查阅和复习。

Factory

What is the Factory Design Pattern?

• When a method returns one of several possible classes that share a common super class.

• Create a new enemy in a game.

• Random number generator picks a number assigned to a specific enemy.

• The factory returns the enemy associated with that number.

• The class is chosen at run time.

Sample Code

• EnemyShip.java

 public abstract class EnemyShip {

     private String name;
private double speed;
private double directionX;
private double directionY;
private double amtDamage; public String getName() { return name; }
public void setName(String newName) { name = newName; } public double getDamage() { return amtDamage; }
public void setDamage(double newDamage) { amtDamage = newDamage; } public void followHeroShip(){ System.out.println(getName() + " is following the hero"); } public void displayEnemyShip(){ System.out.println(getName() + " is on the screen"); } public void enemyShipShoots() { System.out.println(getName() + " attacks and does " + getDamage() + " damage to hero"); } }

• UFOEnemyShip.java

 public class UFOEnemyShip extends EnemyShip {

     public UFOEnemyShip(){

         setName("UFO Enemy Ship");

         setDamage(20.0);

     }

 }

• RocketEnemyShip.java

 public class RocketEnemyShip extends EnemyShip {

     public RocketEnemyShip(){

         setName("Rocket Enemy Ship");

         setDamage(10.0);

     }

 }

• EnemyShipTesting.java

 import java.util.Scanner;

 public class EnemyShipTesting {

     public static void main(String[] args){

         // Create the factory object
EnemyShipFactory shipFactory = new EnemyShipFactory(); // Enemy ship object EnemyShip theEnemy = null; Scanner userInput = new Scanner(System.in); System.out.print("What type of ship? (U / R / B)"); if (userInput.hasNextLine()){ String typeOfShip = userInput.nextLine(); theEnemy = shipFactory.makeEnemyShip(typeOfShip); if(theEnemy != null){ doStuffEnemy(theEnemy); } else System.out.print("Please enter U, R, or B next time"); } /*
EnemyShip theEnemy = null; // Old way of creating objects
// When we use new we are not being dynamic EnemyShip ufoShip = new UFOEnemyShip(); doStuffEnemy(ufoShip); System.out.print("\n"); // ----------------------------------------- // This allows me to make the program more dynamic
// It doesn't close the code from being modified
// and that is bad! // Defines an input stream to watch: keyboard
Scanner userInput = new Scanner(System.in); String enemyShipOption = ""; System.out.print("What type of ship? (U or R)"); if (userInput.hasNextLine()){ enemyShipOption = userInput.nextLine(); } if (enemyShipOption == "U"){ theEnemy = new UFOEnemyShip(); } else if (enemyShipOption == "R"){ theEnemy = new RocketEnemyShip(); } else { theEnemy = new BigUFOEnemyShip(); } doStuffEnemy(theEnemy); // --------------------------------------------
*/ } // Executes methods of the super class public static void doStuffEnemy(EnemyShip anEnemyShip){ anEnemyShip.displayEnemyShip(); anEnemyShip.followHeroShip(); anEnemyShip.enemyShipShoots(); } }

• BigUFOEnemyShip.java

 public class BigUFOEnemyShip extends UFOEnemyShip {

     public BigUFOEnemyShip(){

         setName("Big UFO Enemy Ship");

         setDamage(40.0);

     }

 }

• EnemyShipFactory.java

 // This is a factory thats only job is creating ships
// By encapsulating ship creation, we only have one
// place to make modifications public class EnemyShipFactory{ // This could be used as a static method if we
// are willing to give up subclassing it public EnemyShip makeEnemyShip(String newShipType){ EnemyShip newShip = null; if (newShipType.equals("U")){ return new UFOEnemyShip(); } else if (newShipType.equals("R")){ return new RocketEnemyShip(); } else if (newShipType.equals("B")){ return new BigUFOEnemyShip(); } else return null; } }

Abstract Factory

What is the Abstract Factory Design Pattern?

• It is like a factory, but everything is encapsulated.

• The method that orders the object.

• The factories that build the object.

• The final objects.

• The final objects contain objects that use the Strategy Design Pattern.

• Composition: Object class fields are objects.

What can you do with an Abstract Factory Design Pattern?

• Allows you to create families of related objects without specifying a concrete class.

• Use when you have many objects that can be added, or changed dynamically during runtime.

• You can model anything you can imagine and have those objects interact through common interfaces.

• The Bad: Things can get complicated.

Sample Code

• EnemyShipTesting.java

 public class EnemyShipTesting {

 public static void main(String[] args) {

         // EnemyShipBuilding handles orders for new EnemyShips
// You send it a code using the orderTheShip method &
// it sends the order to the right factory for creation EnemyShipBuilding MakeUFOs = new UFOEnemyShipBuilding(); EnemyShip theGrunt = MakeUFOs.orderTheShip("UFO");
System.out.println(theGrunt + "\n"); EnemyShip theBoss = MakeUFOs.orderTheShip("UFO BOSS");
System.out.println(theBoss + "\n"); } }

• EnemyShipBuilding.java

 public abstract class EnemyShipBuilding {

     // This acts as an ordering mechanism for creating
// EnemyShips that have a weapon, engine & name
// & nothing else // The specific parts used for engine & weapon depend
// upon the String that is passed to this method protected abstract EnemyShip makeEnemyShip(String typeOfShip); // When called a new EnemyShip is made. The specific parts
// are based on the String entered. After the ship is made
// we execute multiple methods in the EnemyShip Object public EnemyShip orderTheShip(String typeOfShip) {
EnemyShip theEnemyShip = makeEnemyShip(typeOfShip); theEnemyShip.makeShip();
theEnemyShip.displayEnemyShip();
theEnemyShip.followHeroShip();
theEnemyShip.enemyShipShoots(); return theEnemyShip; }
}

• UFOEnemyShipBuilding.java

 // This is the only class that needs to change, if you
// want to determine which enemy ships you want to
// provide as an option to build public class UFOEnemyShipBuilding extends EnemyShipBuilding { protected EnemyShip makeEnemyShip(String typeOfShip) {
EnemyShip theEnemyShip = null; // If UFO was sent grab use the factory that knows
// what types of weapons and engines a regular UFO
// needs. The EnemyShip object is returned & given a name if(typeOfShip.equals("UFO")){
EnemyShipFactory shipPartsFactory = new UFOEnemyShipFactory();
theEnemyShip = new UFOEnemyShip(shipPartsFactory);
theEnemyShip.setName("UFO Grunt Ship"); } else // If UFO BOSS was sent grab use the factory that knows
// what types of weapons and engines a Boss UFO
// needs. The EnemyShip object is returned & given a name if(typeOfShip.equals("UFO BOSS")){
EnemyShipFactory shipPartsFactory = new UFOBossEnemyShipFactory();
theEnemyShip = new UFOBossEnemyShip(shipPartsFactory);
theEnemyShip.setName("UFO Boss Ship"); } return theEnemyShip;
}
}

• EnemyShipFactory.java

 // With an Abstract Factory Pattern you won't
// just build ships, but also all of the components
// for the ships // Here is where you define the parts that are required
// if an object wants to be an enemy ship public interface EnemyShipFactory{ public ESWeapon addESGun();
public ESEngine addESEngine(); }

• UFOEnemyShipFactory.java

 // This factory uses the EnemyShipFactory interface
// to create very specific UFO Enemy Ship // This is where we define all of the parts the ship
// will use by defining the methods implemented
// being ESWeapon and ESEngine // The returned object specifies a specific weapon & engine public class UFOEnemyShipFactory implements EnemyShipFactory{ // Defines the weapon object to associate with the ship public ESWeapon addESGun() {
return new ESUFOGun(); // Specific to regular UFO
} // Defines the engine object to associate with the ship public ESEngine addESEngine() {
return new ESUFOEngine(); // Specific to regular UFO
}
}

• UFOBossEnemyShipFactory.java

 // This factory uses the EnemyShipFactory interface
// to create very specific UFO Enemy Ship // This is where we define all of the parts the ship
// will use by defining the methods implemented
// being ESWeapon and ESEngine // The returned object specifies a specific weapon & engine public class UFOBossEnemyShipFactory implements EnemyShipFactory{ // Defines the weapon object to associate with the ship public ESWeapon addESGun() {
return new ESUFOBossGun(); // Specific to Boss UFO
} // Defines the engine object to associate with the ship public ESEngine addESEngine() {
return new ESUFOBossEngine(); // Specific to Boss UFO
} }

• EnemyShip.java

 public abstract class EnemyShip {

     private String name;

     // Newly defined objects that represent weapon & engine
// These can be changed easily by assigning new parts
// in UFOEnemyShipFactory or UFOBossEnemyShipFactory ESWeapon weapon;
ESEngine engine; public String getName() { return name; }
public void setName(String newName) { name = newName; } abstract void makeShip(); // Because I defined the toString method in engine
// when it is printed the String defined in toString goes
// on the screen public void followHeroShip(){ System.out.println(getName() + " is following the hero at " + engine ); } public void displayEnemyShip(){ System.out.println(getName() + " is on the screen"); } public void enemyShipShoots(){ System.out.println(getName() + " attacks and does " + weapon); } // If any EnemyShip object is printed to screen this shows up public String toString(){ String infoOnShip = "The " + name + " has a top speed of " + engine +
" and an attack power of " + weapon; return infoOnShip; } }

• UFOEnemyShip.java

 public class UFOEnemyShip extends EnemyShip{

     // We define the type of ship we want to create
// by stating we want to use the factory that
// makes enemy ships EnemyShipFactory shipFactory; // The enemy ship required parts list is sent to
// this method. They state that the enemy ship
// must have a weapon and engine assigned. That
// object also states the specific parts needed
// to make a regular UFO versus a Boss UFO public UFOEnemyShip(EnemyShipFactory shipFactory){ this.shipFactory = shipFactory; } // EnemyShipBuilding calls this method to build a
// specific UFOEnemyShip void makeShip() { System.out.println("Making enemy ship " + getName()); // The specific weapon & engine needed were passed in
// shipFactory. We are assigning those specific part
// objects to the UFOEnemyShip here weapon = shipFactory.addESGun();
engine = shipFactory.addESEngine(); } }

• UFOBossEnemyShip.java

 public class UFOBossEnemyShip extends EnemyShip{

     // We define the type of ship we want to create
// by stating we want to use the factory that
// makes enemy ships EnemyShipFactory shipFactory; // The enemy ship required parts list is sent to
// this method. They state that the enemy ship
// must have a weapon and engine assigned. That
// object also states the specific parts needed
// to make a Boss UFO versus a Regular UFO public UFOBossEnemyShip(EnemyShipFactory shipFactory){ this.shipFactory = shipFactory; } // EnemyShipBuilding calls this method to build a
// specific UFOBossEnemyShip void makeShip() { // TODO Auto-generated method stub System.out.println("Making enemy ship " + getName()); // The specific weapon & engine needed were passed in
// shipFactory. We are assigning those specific part
// objects to the UFOBossEnemyShip here weapon = shipFactory.addESGun();
engine = shipFactory.addESEngine(); } }

• ESEngine.java

 // Any part that implements the interface ESEngine
// can replace that part in any ship public interface ESEngine{ // User is forced to implement this method
// It outputs the string returned when the
// object is printed public String toString(); }

• ESWeapon.java

 // Any part that implements the interface ESWeapon
// can replace that part in any ship public interface ESWeapon{ // User is forced to implement this method
// It outputs the string returned when the
// object is printed public String toString(); }

• ESUFOGun.java

 // Here we define a basic component of a space ship
// Any part that implements the interface ESWeapon
// can replace that part in any ship public class ESUFOGun implements ESWeapon{ // EnemyShip contains a reference to the object
// ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed
// the following shows on the screen public String toString(){
return "20 damage";
} }

• ESUFOEngine.java

 // Here we define a basic component of a space ship
// Any part that implements the interface ESEngine
// can replace that part in any ship public class ESUFOEngine implements ESEngine{ // EnemyShip contains a reference to the object
// ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed
// the following shows on the screen public String toString(){
return "1000 mph";
} }

• ESUFOBossGun.java

 // Here we define a basic component of a space ship
// Any part that implements the interface ESWeapon
// can replace that part in any ship public class ESUFOBossGun implements ESWeapon{ // EnemyShip contains a reference to the object
// ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed
// the following shows on the screen public String toString(){
return "40 damage";
} }

• ESUFOBossEngine.java

 // Here we define a basic component of a space ship
// Any part that implements the interface ESEngine
// can replace that part in any ship public class ESUFOBossEngine implements ESEngine{ // EnemyShip contains a reference to the object
// ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed
// the following shows on the screen public String toString(){
return "2000 mph";
} }

Singleton

What is the Singleton Design Pattern?

• It is used when you want to eliminate the option of instantiating more than one object.

• I'll Samplenstrate it using a class that holds all the potential Scrabble letters and spits out new ones upon request.

• Each player will share the same potential letter list.

• Each player has their own set of letters.

Sample Code

• Singleton.java

 import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList; public class Singleton { private static Singleton firstInstance = null; String[] scrabbleLetters = {"a", "a", "a", "a", "a", "a", "a", "a", "a",
"b", "b", "c", "c", "d", "d", "d", "d", "e", "e", "e", "e", "e",
"e", "e", "e", "e", "e", "e", "e", "f", "f", "g", "g", "g", "h",
"h", "i", "i", "i", "i", "i", "i", "i", "i", "i", "j", "k", "l",
"l", "l", "l", "m", "m", "n", "n", "n", "n", "n", "n", "o", "o",
"o", "o", "o", "o", "o", "o", "p", "p", "q", "r", "r", "r", "r",
"r", "r", "s", "s", "s", "s", "t", "t", "t", "t", "t", "t", "u",
"u", "u", "u", "v", "v", "w", "w", "x", "y", "y", "z",}; private LinkedList<String> letterList = new LinkedList<String> (Arrays.asList(scrabbleLetters)); // Used to slow down 1st thread
static boolean firstThread = true; // Created to keep users from instantiation
// Only Singleton will be able to instantiate this class private Singleton() { } // We could make getInstance a synchronized method to force
// every thread to wait its turn. That way only one thread
// can access a method at a time. This can really slow everything
// down though
// public static synchronized Singleton getInstance() public static Singleton getInstance() {
if(firstInstance == null) { // This is here to test what happens if threads try
// to create instances of this class if(firstThread){ firstThread = false; try {
Thread.currentThread();
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace();
}
} // Here we just use synchronized when the first object
// is created synchronized(Singleton.class){ if(firstInstance == null) {
// If the instance isn't needed it isn't created
// This is known as lazy instantiation firstInstance = new Singleton(); // Shuffle the letters in the list
Collections.shuffle(firstInstance.letterList); } } } // Under either circumstance this returns the instance return firstInstance;
} public LinkedList<String> getLetterList(){ return firstInstance.letterList; } public LinkedList<String> getTiles(int howManyTiles){ // Tiles to be returned to the user LinkedList<String> tilesToSend = new LinkedList<String>(); // Cycle through the LinkedList while adding the starting
// Strings to the to be returned LinkedList while deleting
// them from letterList for(int i = 0; i <= howManyTiles; i++){ tilesToSend.add(firstInstance.letterList.remove(0)); } // Return the number of letter tiles requested return tilesToSend; } }

• ScrabbleTest.java

 import java.util.LinkedList;

 public class ScrabbleTest {

     public static void main(String[] args){

         // How you create a new instance of Singleton

         Singleton newInstance = Singleton.getInstance();

         // Get unique id for instance object

         System.out.println("1st Instance ID: " + System.identityHashCode(newInstance));

         // Get all of the letters stored in the List

         System.out.println(newInstance.getLetterList());

         LinkedList<String> playerOneTiles = newInstance.getTiles(7);

         System.out.println("Player 1: " + playerOneTiles);

         System.out.println(newInstance.getLetterList());

         // Try to make another instance of Singleton
// This doesn't work because the constructor is private // Singleton instanceTwo = new Singleton(); // Try getting a new instance using getInstance Singleton instanceTwo = Singleton.getInstance(); // Get unique id for the new instance object System.out.println("2nd Instance ID: " + System.identityHashCode(instanceTwo)); // This returns the value of the first instance created System.out.println(instanceTwo.getLetterList()); // Player 2 draws 7 tiles LinkedList<String> playerTwoTiles = newInstance.getTiles(7); System.out.println("Player 2: " + playerTwoTiles); } }

• ScrabbleTestThreads.java

 public class ScrabbleTestThreads{

     public static void main(String[] args){

         // Create a new Thread created using the Runnable interface
// Execute the code in run after 10 seconds Runnable getTiles = new GetTheTiles(); Runnable getTilesAgain = new GetTheTiles(); // Call for the code in the method run to execute new Thread(getTiles).start();
new Thread(getTilesAgain).start(); } }

• GetTheTiles.java

 import java.util.LinkedList;

 public class GetTheTiles implements Runnable {

     public void run(){

             // How you create a new instance of Singleton

             Singleton newInstance = Singleton.getInstance();

             // Get unique id for instance object

             System.out.println("1st Instance ID: " + System.identityHashCode(newInstance));

             // Get all of the letters stored in the List

             System.out.println(newInstance.getLetterList());

             LinkedList<String> playerOneTiles = newInstance.getTiles(7);

             System.out.println("Player 1: " + playerOneTiles);

         System.out.println("Got Tiles");
} }

Builder

What is the Builder Design Pattern?

• Pattern used to create objects made from a bunch of other objects.

• When you want to build an object made up from other objects.

• When you want the creation of these parts to be independent of the main object.

• Hide the creation of the parts from the client so both aren't dependent.

• The builder knows the specifics and nobody else dose.

Sample Code

• RobotPlan.java

 // This is the interface that will be returned from the builder

 public interface RobotPlan{

     public void setRobotHead(String head);

     public void setRobotTorso(String torso);

     public void setRobotArms(String arms);

     public void setRobotLegs(String legs);

 }

• Robot.java

 // The concrete Robot class based on the RobotPlan interface

 public class Robot implements RobotPlan{

     private String robotHead;
private String robotTorso;
private String robotArms;
private String robotLegs; public void setRobotHead(String head) { robotHead = head; } public String getRobotHead(){ return robotHead; } public void setRobotTorso(String torso) { robotTorso = torso; } public String getRobotTorso(){ return robotTorso; } public void setRobotArms(String arms) { robotArms = arms; } public String getRobotArms(){ return robotArms; } public void setRobotLegs(String legs) { robotLegs = legs; } public String getRobotLegs(){ return robotLegs; } }

• RobotBuilder.java

 // Defines the methods needed for creating parts
// for the robot public interface RobotBuilder { public void buildRobotHead(); public void buildRobotTorso(); public void buildRobotArms(); public void buildRobotLegs(); public Robot getRobot(); }

• OldRobotBuilder.java

 // The concrete builder class that assembles the parts
// of the finished Robot object public class OldRobotBuilder implements RobotBuilder { private Robot robot; public OldRobotBuilder() { this.robot = new Robot(); } public void buildRobotHead() { robot.setRobotHead("Tin Head"); } public void buildRobotTorso() { robot.setRobotTorso("Tin Torso"); } public void buildRobotArms() { robot.setRobotArms("Blowtorch Arms"); } public void buildRobotLegs() { robot.setRobotLegs("Rollar Skates"); } public Robot getRobot() { return this.robot;
} }

• RobotEngineer.java

 // The director / engineer class creates a Robot using the
// builder interface that is defined (OldRobotBuilder) public class RobotEngineer { private RobotBuilder robotBuilder; // OldRobotBuilder specification is sent to the engineer public RobotEngineer(RobotBuilder robotBuilder){ this.robotBuilder = robotBuilder; } // Return the Robot made from the OldRobotBuilder spec public Robot getRobot(){ return this.robotBuilder.getRobot(); } // Execute the methods specific to the RobotBuilder
// that implements RobotBuilder (OldRobotBuilder) public void makeRobot() { this.robotBuilder.buildRobotHead();
this.robotBuilder.buildRobotTorso();
this.robotBuilder.buildRobotArms();
this.robotBuilder.buildRobotLegs(); } }

• TestRobotBuilder.java

 public class TestRobotBuilder {

     public static void main(String[] args){

         // Get a RobotBuilder of type OldRobotBuilder

         RobotBuilder oldStyleRobot = new OldRobotBuilder();

         // Pass the OldRobotBuilder specification to the engineer

         RobotEngineer robotEngineer = new RobotEngineer(oldStyleRobot);

         // Tell the engineer to make the Robot using the specifications
// of the OldRobotBuilder class robotEngineer.makeRobot(); // The engineer returns the right robot based off of the spec
// sent to it on line 11 Robot firstRobot = robotEngineer.getRobot(); System.out.println("Robot Built"); System.out.println("Robot Head Type: " + firstRobot.getRobotHead()); System.out.println("Robot Torso Type: " + firstRobot.getRobotTorso()); System.out.println("Robot Arm Type: " + firstRobot.getRobotArms()); System.out.println("Robot Leg Type: " + firstRobot.getRobotLegs()); } }

Prototype

What is the Prototype Design Pattern?

• Creating new objects (instances) by cloning (copying) other objects.

• Allows for adding of any subclass instance of a known super class at run time.

• When there are numerous potential classes that you want to only use if needed at runtime.

• Reduces the need for creating subclasses.

Sample Code

• Animal.java

 // By making this class cloneable you are telling Java
// that it is ok to copy instances of this class
// These instance copies have different results when
// System.identityHashCode(System.identityHashCode(bike))
// is called public interface Animal extends Cloneable { public Animal makeCopy(); }

• Sheep.java

 public class Sheep implements Animal {

     public Sheep(){

         System.out.println("Sheep is Made");

     }

     public Animal makeCopy() {

         System.out.println("Sheep is Being Made");

         Sheep sheepObject = null;

         try {

             // Calls the Animal super classes clone()
// Then casts the results to Sheep sheepObject = (Sheep) super.clone(); } // If Animal didn't extend Cloneable this error
// is thrown catch (CloneNotSupportedException e) { System.out.println("The Sheep was Turned to Mush"); e.printStackTrace(); } return sheepObject;
} public String toString(){ return "Dolly is my Hero, Baaaaa"; } }

• CloneFactory.java

 public class CloneFactory {

     // Receives any Animal, or Animal subclass and
// makes a copy of it and stores it in its own
// location in memory // CloneFactory has no idea what these objects are
// except that they are subclasses of Animal public Animal getClone(Animal animalSample) { // Because of Polymorphism the Sheeps makeCopy()
// is called here instead of Animals return animalSample.makeCopy(); } }

• TestCloning.java

 public class TestCloning {

     public static void main(String[] args){

         // Handles routing makeCopy method calls to the
// right subclasses of Animal CloneFactory animalMaker = new CloneFactory(); // Creates a new Sheep instance Sheep sally = new Sheep(); // Creates a clone of Sally and stores it in its own
// memory location Sheep clonedSheep = (Sheep) animalMaker.getClone(sally); // These are exact copies of each other System.out.println(sally); System.out.println(clonedSheep); System.out.println("Sally HashCode: " + System.identityHashCode(System.identityHashCode(sally))); System.out.println("Clone HashCode: " + System.identityHashCode(System.identityHashCode(clonedSheep)));
} }

作者:netoxi
出处:http://www.cnblogs.com/netoxi
本文版权归作者和博客园共有,欢迎转载,未经同意须保留此段声明,且在文章页面明显位置给出原文连接。欢迎指正与交流。

设计模式教程(Design Patterns Tutorial)笔记之一 创建型模式(Creational Patterns)的更多相关文章

  1. Java 23种设计模式详尽分析与实例解析之一--创建型模式

    面向对象的设计原则 常用的面向对象设计原则包括7个,这些原则并不是独立存在的,它们相互依赖.互为补充. Java设计模式 创建型模式 简单工厂模式 模式动机: 考虑一个简单的软件应用场景,一个软件系统 ...

  2. C#面向对象设计模式纵横谈——3.Abstract Factory 抽象工厂(创建型模式)

    动机(Motivation) 在软件系统中经常面临着“一系列相互依赖的对象”的创建工作,同时,由于需求变化,往往存在更多系列对象的创建工作.如何应对这种变化?如何绕过常规对象的创建,提供一种“封装机制 ...

  3. 设计模式之美:Creational Patterns(创建型模式)

    创建型模式(Creational Patterns)抽象了对象实例化过程. 它们帮助一个系统独立于如何创建.组合和表示它的那些对象. 一个类创建型模式使用继承改变被实例化的类. 一个对象创建型模式将实 ...

  4. Typescript玩转设计模式 之 创建型模式

    作者简介 joey 蚂蚁金服·数据体验技术团队 前言 我们团队的工作是用单页面应用的方式实现web工具.涉及到数万到十数万行的前端代码的管理,而且项目周期长达数年. 怎么样很好地管理好这种量级的前端代 ...

  5. 设计模式01: Singleton 单例模式(创建型模式)

    Singleton 单例模式(创建型模式) 动机(Motivation)当进行软件开发是会有这样一种需求:在系统中只有存在一个实例才能确保它们的逻辑正确性.以及良好的效率.这应该是类设计者的责任,而不 ...

  6. Singleton patterns 单件(创建型模式)

    1.模式分类 1.1  从目的来看: •      – 创建型(Creational)模式:负责对象创建. •      – 结构型(Structural)模式:处理类与对象间的组合. •      ...

  7. Java设计模式 - 单例模式(创建型模式)

    单例模式我在上学期看一些资料时候学习过,没想到这学期的软件体系结构就有设计模式学习,不过看似篇幅不大,介绍得比较简单,在这里我总结下单例模式,一来整理之前的笔记,二来也算是预习复习课程了. 概述 单例 ...

  8. C#面向对象设计模式纵横谈——2.Singleton 单件(创建型模式)

    一:模式分类 从目的来看: 创建型(Creational)模式:负责对象创建. 结构型(Structural)模式:处理类与对象间的组合. 行为型(Behavioral)模式:类与对象交互中的职责分配 ...

  9. Java设计模式之创建型模式

    创建型模式分为五类:工厂方法模式.抽象工厂模式.单例模式.建造者模式.原型模式 一.工厂方法模式:接口-实现类.工厂类

随机推荐

  1. selenium实现淘宝的商品爬取

    一.问题 本次利用selenium自动化测试,完成对淘宝的爬取,这样可以避免一些反爬的措施,也是一种爬虫常用的手段.本次实战的难点: 1.如何利用selenium绕过淘宝的登录界面 2.获取淘宝的页面 ...

  2. 微信浏览器Ajax请求返回值走error

    微信浏览器Ajax post请求是返回值走的error $.ajax({ type: "POST", url: "https://XXXX", cache: f ...

  3. VM下载安装

    VM下载 VM是一款收费软件,要找有密钥的下载. 我的网盘 > 软件 > 常用电脑工具 > VM VM安装 参考链接中的安装步骤 http://blog.java1234.com/b ...

  4. mysql的一些操作命令

    1.查看mysql数据库 SHOW DATABASES;(;号一定要加) 2.创建root用户密码 mysqladmin -u root password "new_password&quo ...

  5. Cannot set property 'onclick' of null报错

    经常几个页面使用公共js文件, 原来遇到也没留意, 原来是本页面执行的时候, 其他页面也在执行并赋予id于onclick. 因为页面是正常情况下是不存在null和undefined if(null){ ...

  6. go的数据库操作mysql

    go get github.com/go-sql-driver/mysql package main; import ( "database/sql" _ "github ...

  7. Alpha冲刺 - (7/10)

    Part.1 开篇 队名:彳艮彳亍团队组长博客:戳我进入作业博客:班级博客本次作业的链接 Part.2 成员汇报 组员1(组长)柯奇豪 过去两天完成了哪些任务 改用更易用的springboot+myb ...

  8. ESP-IDF版本2.1.1

    版本2.1.1是一个错误修复版本.它包括对KRACK和BlueBorne漏洞的修复. 版本2.1.1的文档可在http://esp-idf.readthedocs.io/en/v2.1.1/上找到. ...

  9. 设计一个BCD码计数器。

    BCD码计数器的定义: 对于机器语言,机器与人不同,为了让人更好的了解机器语言的数据输出,选用4位二进制数据表示十进制里的每位数据,这便是BCD码. 以下便是BCD码与十进制对应的码表 0------ ...

  10. 关于HttpClient,HttpURLConnection,OkHttp的用法

    1 HttpClient入门实例 1.1发送get请求 /** * HttpClient发送get请求 * @param url 请求地址 * @return * @throws IOExceptio ...