Java design mode of the sharing meta-mode

Source: Internet
Author: User

Define a common internal

Public interface Clessflyweight {
void SetColor (String c);
String GetColor ();
void display (coordinate c);
}
Class Concretechess implements clessflyweight{

private String color;


Public concretechess (String color) {
Super ();
This.color = color;
}

@Override
Public String GetColor () {
TODO auto-generated Method Stub
return color;
}

@Override
public void SetColor (String c) {
TODO auto-generated Method Stub
This.color=c;
}

@Override
public void display (coordinate c) {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN ("Pawn Color" +color);
System.out.println ("Pawn Position:" +c.getx () +c.gety ());
}

}

Define a sharing factory

/**
*
* Enjoy the Yuan factory class
* @author Zzdxw
*
*/
public class Clessflyweightfactory {
Enjoy meta pool
private static map<string, clessflyweight> map=new hashmap<string,clessflyweight> ();
public static clessflyweight getchess (String color) {
if (map.get (color)!=null) {
return map.get (color);
}else{
Clessflyweight cfw=new concretechess (color);
Map.put (COLOR,CFW);
return CFW;
}
}
}

Defines an external

public class Coordinate {
private int x, y;

public coordinate (int x, int y) {
Super ();
this.x = x;
This.y = y;
}

public int GetX () {
return x;
}

public void SetX (int x) {
this.x = x;
}

public int GetY () {
return y;
}

public void sety (int y) {
This.y = y;
}

}

Client Testing

public class Client {
public static void Main (string[] args) {
Clessflyweight chess1=clessflyweightfactory.getchess ("Black");
Clessflyweight chess2=clessflyweightfactory.getchess ("Black");
System.out.println (CHESS1);
System.out.println (CHESS2);
}
}

Java design mode of the sharing meta-mode

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.