Code for Java 23 design modes

Source: Internet
Author: User
Package SCSI. test;

Import java. Io .*;
Import java. util .*;

***************

// Factory method 1
// The specific construction algorithm of 1 and the specific product constructed by 2 are implemented by sub-classes
Interface product {
}

// Or I also provide a factory interface inherited by this abstract class

Abstract class factory {
Abstract Public Product FMD ();

// I think the existence of this method is a supplement to the factorymethod method.
// For example, you can assign values to the generated object, calculate the value payable to the generated object, and the daily value before and after the generated object.
// These are all public. The main algorithm used to generate the product is in factorymethod,
// This method only plays an auxiliary role, which is also a way of thinking, implementing a specific algorithm in a method
// Instead of calling this method directly, I use another method to encapsulate it, and the result is more flexible.
// The Sub-class must implement factorymethod.
// This method is a templatemethod
Public Product creat (){
Product Pd = NULL;

System. Out. println ("before operation ");

Pd = fmd ();

System. out. println ("end operation ");

Return pd;
}
}

Class Product1 implements Product {
}

Class Factory1 extends Factory {
Public Product fmd (){
Product pd = new Product1 ();
Return pd;
}
}

// FactroyMethod 2
// This method is simple and practical
Interface Producta {
}

Interface Factorya {
Producta create ();
}

Class Producta1 implements Producta {}

Class Factorya1 implements Factorya {
Public Producta create (){
Producta pda = null;
Pda = new Producta1 ();
Return pda;
}
}

// AbstractFactory
// The difference between AbstractFactory and FactoryMethod is that AbstractFactory creates multiple products.
// It seems that this mode is useless.

// Of course there can be more interfaces
Interface Apda {}

Interface Apdb {}

Interface Afactory {
Apda createA ();
Apdb createB ();
}

Class Apda1 implements Apda {}

Class Apdb1 implements Apdb {}

// There are several interfaces and there are several corresponding methods
Class Afactory1 implements Afactory {
Public Apda createA (){
Apda apda = null;
Apda = new Apda1 ();
Return apda;
}

Public Apdb createB (){
Apdb apdb = null;
Apdb = new Apdb1 ();
Return apdb;
}
}

// Builder
// The generation of a product is divided into generating parts and assembling parts. Each part of different products is generated in different ways.
// The assembly method is the same. The component generation is abstracted as an interface method, while the assembly method uses a TemplateMethod method.

Interface Cpda {}

Class Cpda1 implements Cpda {}

Interface BuilderI {
Void buildPart1 ();
Void buildPart2 ();

Void initPd ();
Cpda getPd ();
}

Abstract class BuilderA implements BuilderI {
Cpda cpda;

Public Cpda getPd (){
InitPd ();

// Set the object content
BuildPart1 ();
BuildPart2 ();

Return cpda;
}
}

Class Builder extends BuilderA {
Public void buildPart1 (){
System. out. println (cpda );
}

Public void buildPart2 (){
System. out. println (cpda );
}

Public void initPd (){
Cpda = new Cpda1 ();
}
}

// A simple product generation implementation
// 1
Abstract class Fy {
Public abstract void med1 ();

Static class Fy1 extends Fy {
Public void med1 (){
}
}

Public static Fy getInstance (){
Fy fy = new Fy1 ();
Return fy;

// Fy fy = new Fy1 () {// this anonymous internal class is static !!
// Public void med1 (){
//}
//};
// Return fy;
}
}

// 2
Interface Pdd {}

Class Pdd1 implements Pdd {}

Abstract class Fya {
Public static Pdd getPd (){
Pdd pdd = new Pdd1 ();
Return pdd;
}
}

// Prototype is clone in java, which also contains deep copy and shallow copy.
Class CloneObja {
Public CloneObja MyClone (){
Return new CloneObja ();
}
}

Class CloneObjb {
Public CloneObjb MyClone () throws Throwable {
CloneObjb cobj = null;
Cobj = (CloneObjb) pcl (this );
Return cobj;
}

// Deep copy Algorithm
Private Object pcl (Object obj) throws Throwable {
Bytearrayoutputstreambao = new ByteArrayOutputStream (1000 );
ObjectOutputStream objo = new ObjectOutputStream (bao );
Objo. writeObject (obj );

ByteArrayInputStream bai = new ByteArrayInputStream (bao. toByteArray ());
ObjectInputStream obji = new ObjectInputStream (bai );

Object objr = obji. readObject ();
Return objr;
}
}

// Singleton
// A class has only one object, such as a thread pool and a cache.
Class Singleton1 {
Public static singleton1 instance = new singleton1 ();

Private singleton1 (){
}

Public static singleton1 getinstance (){
Return instance;
}
}

Class singleton2 {
Public static singleton2 instance;

Private singleton2 (){
}

// Public static singleton2 getinstance (){
// If (instance = NULL ){
// Instance = new singleton2 ();
//}
//
// Return instance;
//}

Public static singleton2 getinstance (){
Synchronized (singleton2.class ){
If (instance = NULL ){
Instance = new singleton2 ();
}
}

Return instance;
}
}


 
// *********** Structural mode **********

// Adapter
// There are two basic methods: Reference and inheritance.
// Convert an interface that does not conform to the standard to an interface that complies with the standard. The interface is modified mainly by the increase or decrease of parameters,
// Return value type. Of course, there is a method name.
// It seems that this is another form of encapsulation. It encapsulates useful method encapsulation (calling functional methods in methods ),
// Use class encapsulation (first pass in the Class Object of the function method, by calling the function method of this object)

// Use the reference format
Class Adapteea {
Public void kk (){}
}

Interface Targeta {
String vv (int I, int k );
}

Class adaptors implements Targeta {
Adapteea ade;

Public adaptors (Adapteea ade ){
This. ade = ade;
}

Public String vv (int I, int k ){
// The specific business method is implemented in Adaptee.
// Only functions as Interface Conversion
// Call this method by referencing
Ade. kk ();
Return null;
}
}

// Use the inherited
Class Adapteeb {
Public void kk (){}
}

Interface Targetb {
String vv (int I, int k );
}

Class Adapterb extends Adapteeb implements Targetb {
Public String vv (int I, int k ){
// Call this method through inheritance
Kk ();
Return null;
}
}

// Proxy
Interface Subject {
Void request ();
}

Class realSubject implements Subject {
Public void request (){
// Do the real business
}
}

Class Proxy implements Subject {
Subject subject;

Public Proxy (Subject subject ){
This. subject = subject;
}

Public void request (){
System. out. println ("do something ");

Subject. request ();

System. out. println ("do something ");
}
}

// Bridge
// The perception is the implementation of polymorphism.

Interface Imp {
Void operation ();
}

Class Cimp1 implements Imp {
Public void operation (){
System. out. println ("1 ");
}
}

Class Cimp2 implements Imp {
Public void operation (){
System. out. println ("2 ");
}
}

Class Invoker {
Imp imp = new Cimp1 ();

Public void invoke (){
Imp. operation ();
}
}

// Composite

Interface Component {
Void operation ();

Void add (Component component );

Void remove (Component component );
}

Class Leaf implements Component {
Public void operation (){
System. out. println ("an operation ");
}

Public void add (Component component ){
Throw new UnsupportedOperationException ();
}

Public void remove (Component component ){
Throw new UnsupportedOperationException ();
}
}

Class Composite implements Component {
List components = new ArrayList ();

Public void operation (){
Component component = null;

Iterator it = components. iterator ();
While (it. hasNext ()){
// Do not know whether the component object is leaf or composite,
// If it is leaf, the operation is implemented directly. If it is composite, recursive call is continued.
Component = (Component) it. next ();
Component. operation ();
}
}

Public void add (Component component ){
Components. add (component );
}

Public void remove (Component component ){
Components. remove (component );
}
}

// Decorator
// When I extend the functions of a class, I can use inheritance, but it is not flexible enough, so I chose
// In another form, both reference and inheritance can have certain usage capabilities for objects, and the use of references will be more flexible.
// Ensure that the original function is appended rather than modified. Otherwise, you can only rewrite the method or use the new method.
// Note that the concrete can be new directly,
// The decorator must use another decorator object to generate an object.
// Use object encapsulation and public interfaces
// The Decorator chain can contain multiple elements

Interface Componenta {
Void operation ();
}

Class ConcreteComponent implements Componenta {
Public void operation (){
System. out. println ("do something ");
}
}

Class Decorator implements Componenta {
Private Componenta component;

Public Decorator (Componenta component ){
This. component = component;
}

Public void operation (){
// Do something before

Component. operation ();

// Do something after
}
}

// Facade
// A very practical design mode. I can provide external interfaces of interest.

Class Obj1 {
Public void ope1 (){}
Public void ope2 (){}
}

Class Obj2 {
Public void ope1 (){}
Public void ope2 (){}
}

Class Facade {
// I got a concise and clear interface
Public void fdMethod (){
Obj1 obj1 = new Obj1 ();
Obj2 obj2 = new Obj2 ();

Obj1.ope1 ();
Obj2.ope2 ();
}
}

// Flyweight

*************

// Chain of Responsibility
// Similar to the implementation form of Decorator,
// Decorator adds the function on the original method, while
// Chain indicates that if the signal is not currently processed, it is transferred to the next node for processing.
// I can use the if branch to achieve the same effect, but it is not flexible enough. Each node on the chain can be replaced and increased.
// More flexible. We can design interfaces to add and delete nodes to achieve more convenient results.
// This is a chain structure. Have you ever thought of using a ring structure?

Interface Handler {
Void handRequest (int signal );
}

Class CHandler1 implements Handler {
Private Handler handler;

Public CHandler1 (Handler handler ){
This. handler = handler;
}

Public void handRequest (int signal ){
If (signal = 1 ){
System. out. println ("handle signal 1 ");
}
Else {
Handler. handRequest (signal );
}
}
}

Class CHandler2 implements Handler {
Private Handler handler;

Public CHandler2 (Handler handler ){
This. handler = handler;
}

Public void handRequest (int signal ){
If (signal = 2 ){
System. out. println ("handle signal 2 ");
}
Else {
Handler. handRequest (signal );
}
}
}

Class CHandler3 implements Handler {
Public void handRequest (int signal ){
If (signal = 3 ){
System. out. println ("handle signal 3 ");
}
Else {
Throw new Error ("can't handle signal ");
}
}
}

Class ChainClient {
Public static void main (String [] args ){
Handler h3 = new CHandler3 ();
Handler h2 = new CHandler2 (h3 );
Handler h1 = new CHandler1 (h2 );

H1.handRequest (2 );
}
}

// Interpreter
// Similar to Composite, except for the final and non-final characters

// Template Method

Abstract class TemplateMethod {
Abstract void amd1 ();

Abstract void amd2 ();

// This Method is a Template Method.
Public void tmd (){
Amd1 ();
Amd2 ();
}
}

// State

// Standard type
// The status and operation should not be coupled.
Class Contexta {
Private State st;

Public Contexta (int nst ){
ChangeStfromNum (nst );
}

Public void changeStfromNum (int nst ){
If (nst = 1 ){
St = new CStatea1 ();
}
Else if (nst = 2 ){
St = new CStatea2 ();
}

Throw new Error ("bad state ");
}

Void request (){
St. handle (this );
}
}

Interface State {
Void handle (Contexta context );
}

Class CStatea1 implements State {
Public void handle (Contexta context ){
System. out. println ("state 1 ");
// You may need to change the status during the processing of a State. For example, you can disable this effect immediately after it is enabled.
// Context. changeStfromNum (2 );
}
}

Class CStatea2 implements State {
Public void handle (Contexta context ){
System. out. println ("state 2 ");
}
}

// Factory type
// Generate different states based on the state failure

// Class StateFactory {
// Public static State getStateInstance (int num ){
// State st = null;
//
// If (num = 1 ){
// St = new CStatea1 ();
//}
// Else if (num = 2 ){
// St = new CStatea2 ();
//}
//
// Return st;
//}
//}

// Strategy
// Similar to Bridge, it is a multi-state representation.

// Visitor
// Bidirectional reference. Use another class to call your own method and access your data structure.
Interface Visitor {
Void visitElement (Elementd element );
}

Class CVisitor implements Visitor {
Public void visitElement (Elementd element ){
Element. operation ();
}
}

Interface Elementd {
Void accept (Visitor visitor );

Void operation ();
}

Class CElementd implements Elementd {
Public void accept (Visitor visitor ){
Visitor. visitElement (this );
}

Public void operation (){
// The actual operation is here
}
}

Class Clientd {
Public static void main (){
Elementd elm = new CElementd ();
Visitor vis = new CVisitor ();

Vis. visitElement (elm );
}
}

// Iteraotr
// Use the iterator to perform sequential iteration on the data structure of a class

Interface Structure {
Interface Iteratora {
Void first ();

Boolean hasElement ();

Object next ();

}
}

Class Structure1 implements Structure {
Object [] objs = new Object [1, 100];

// Use an internal class to have full access to the Struture1 Data Structure
Class Iteratora1 implements Iteratora {
Int index = 0;

Public void first (){
Index = 0;
}

Public boolean hasElement (){
Return index <100;
}

Public Object next (){
Object obj = null;

If (hasElement ()){
Obj = objs [index];
Index ++;
}

Return obj;
}
}
}

// Meditor

Class A1 {
Public void operation1 (){}
Public void operation2 (){}
}

Class A2 {
Public void operation1 (){}
Public void operation2 (){}
}

Class Mediator {
A1 a1;
A2 a2;

Public Mediator (A1 a1, A2 a2 ){
This. a1 = a1;
This. a2 = a2;

}

// If I want to implement this function, I may put it in A1.
// But this coupling is large, so I don't want to reference A2 objects in A1,
// So I used Mediator as the intermediary
Public void mmed1 (){
A1.operation1 ();
A2.operation2 ();
}

Public void mmed2 (){
A2.operation1 ();
A1.operation2 ();
}
}

// Command
// I think the method is converted into a class

Class extends er {
Public void action1 (){}

Public void action2 (){}
}

Interface Command {
Void Execute ();
}

Class CCommand1 implements Command {
Private aggreger extends er;

Public CCommand1 (extends er extends ER ){
This. Cycler = Cycler;
}

Public void Execute (){
Cycler. action1 ();
}
}

Class CCommand2 implements Command {
Private aggreger extends er;

Public CCommand2 (extends er extends ER ){
This. Cycler = Cycler;
}

Public void Execute (){
Explorer. action2 ();
}
}

// Observer
// It seems that this mode is useless.
// However, if I have a thread that monitors the Subject status
// If the status of the Observer changes, the status of the Observer is changed and some operations are performed.
// The Observer and the Visitor are similar in that they both have two-way references.
// Subject can register many observers

Interface Subjectb {
Void attach (Observer observer );

Void detach (Observer observer );

Void mypolicy ();

Int getstate ();

Void setstate (INT State );
}

Class subjectb1 implements subjectb {
List Observers = new arraylist ();
Int state;

Public void attach (Observer observer ){
Observers. Add (observer );
}

Public void detach (Observer observer ){
Observers. Remove (observer );
}

Public void mypolicy (){
Observer observer = NULL;
Iterator it = observers. iterator ();

While (it. hasnext ()){
Observer = (observer) it. Next ();
Observer. Update ();
}
}

Public int getstate (){
Return state;
}

Public void setState (int state ){
This. state = state;
}
}

Interface Observer {
Void Update ();
}

Class Observer1 implements Observer {
Subjectb subject;
Int state;

Public Observer1 (Subjectb subject ){
This. subject = subject;
}

Public void Update (){
This. state = subject. getState ();
}

Public void operation (){
// Some state-based operations
}
}

// Memento
// It seems that this mode is useless.

Class Memento {
Int state;

Public int getState (){
Return state;
}

Public void setState (int state ){
This. state = state;
}
}

Class Originator {
Int state;

Public void setMemento (Memento memento ){
State = memento. getState ();
}

Public Memento createMemento (){
Memento memento = new Memento ();
Memento. setState (1 );
Return memento;
}

Public int getState (){
Return state;
}

Public void setState (int state ){
This. state = state;
}
}

Class careTaker {
Memento memento;

Public void saverMemento (Memento memento ){
This. memento = memento;
}

Public Memento retrieveMemento (){
Return memento;
}
}

// The program is finally executed in sequence, and is spliced by the disconnected operations.
// Concatenate codes of different classes through reference.
// It is equivalent to having the ability to access data structures and methods.
// Similar. For example, I want to extract a method from a class because this method depends on the data and other methods of this class.
// It is not feasible to directly remove the code, but if we have references to such objects
// Internal, so we can remove this method with reference
Public class tt1 {
Public static void main (String [] args ){
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.