经常使用的方案,公认为正确或相对正确
package simplefactory; class BaseView { } abstract class PicView extends BaseView { } abstract class VideoView extends BaseView { } class FeedPicView extends PicView { } class FeedVideoView extends VideoView { } class FeedFactory { public static BaseView createView(String type) { switch (type) { case "pic" : return new FeedPicView(); case "video" : return new FeedVideoView(); } return null ; } } public class SimpleFactoryDemo { public static void main(String[] args) { BaseView picView = FeedFactory.createView( "pic" ); BaseView videoView = FeedFactory.createView( "video" ); System.out.println(picView.getClass().getSimpleName() + " " + videoView.getClass().getSimpleName()); } }
package abstractfactory; class BaseView { } abstract class PicView extends BaseView { } abstract class VideoView extends BaseView { } class FeedPicView extends PicView { } class FeedVideoView extends VideoView { } class RecommendPicView extends PicView { } class RecommendVideoView extends VideoView { } abstract class ViewFactory { abstract PicView createPicView(); abstract VideoView createVideoView(); } class FeedViewFactory extends ViewFactory { @Override PicView createPicView() { return new FeedPicView(); } @Override VideoView createVideoView() { return new FeedVideoView(); } } class RecommendViewFactory extends ViewFactory { @Override PicView createPicView() { return new RecommendPicView(); } @Override VideoView createVideoView() { return new RecommendVideoView(); } } public class AbstractFactoryDemo { public static void main(String[] args) { // 在feed列表中 displayViews( new FeedViewFactory()); // 在recommend列表中 displayViews( new RecommendViewFactory()); } public static void displayViews(ViewFactory factory) { PicView picView = factory.createPicView(); VideoView videoView = factory.createVideoView(); System.out.println(picView.getClass().getSimpleName() + " " + videoView.getClass().getSimpleName()); } }
package builder; import android.net.Uri; public class BuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append( "This " ); sb.append( "is " ); sb.append( "a " ); sb.append( "demo " ); sb.append( "for " ); sb.append( "Builder." ); System.out.println(sb.toString()); } public static void uriBuilderDemo(){ Uri.Builder ub = new Uri.Builder(); ub.scheme( "http" ); ub.authority( "api.sina.com:8080" ); ub.appendPath( "list.json" ); ub.appendQueryParameter( "wm" , "0560" ); System.out.println(ub.build().toString()); } }
package prototype; import java.util.ArrayList; class NewsItem implements Cloneable { private String id = "" ; private String title = "" ; private String source = "" ; private String link = "" ; private int comment; private String category = "" ; private ArrayList<String> pv = new ArrayList<String>(); private ArrayList<String> monitor = new ArrayList<String>();; @Override public NewsItem clone() throws CloneNotSupportedException { NewsItem obj = (NewsItem) super .clone(); obj.pv = (ArrayList<String>) pv.clone(); obj.monitor = (ArrayList<String>) monitor.clone(); return obj; } } class VideoNewsItem implements Cloneable { private VideoInfo video_info = new VideoInfo(); @Override public VideoNewsItem clone() throws CloneNotSupportedException { VideoNewsItem item = (VideoNewsItem) super .clone(); item.video_info = video_info.clone(); return item; } } class VideoInfo implements Cloneable { private String pic = "" ; private String url = "" ; private String runtime = "" ; private String playnumber = "" ; private String type = "" ; @Override public VideoInfo clone() throws CloneNotSupportedException { return (VideoInfo) super .clone(); } } public class PrototypeDemo { public static void main(String[] args) throws CloneNotSupportedException { VideoNewsItem item1 = new VideoNewsItem(); VideoNewsItem item2 = item1.clone(); System.out.println(item1==item2); } }
package decorator; interface Number { public String getNumber(); } class PhoneNumber implements Number { private String number; public PhoneNumber(String number) { this .number = number; } @Override public String getNumber() { return number; } } class CityDecorator implements Number { private Number number; public CityDecorator(Number number) { this .number = number; } @Override public String getNumber() { return "010-" + number.getNumber(); } } class NationDecorator implements Number { private Number number; public NationDecorator(Number number) { this .number = number; } @Override public String getNumber() { return "+86-" + number.getNumber(); } } class AsteriskDecorator implements Number { private Number number; public AsteriskDecorator(Number number) { this .number = number; } @Override public String getNumber() { return "***" + number.getNumber() + "***" ; } } public class DecoratorDemo { public static void main(String[] args) { Number number = null ; number = new PhoneNumber( "82675588" ); number = new CityDecorator(number); number = new NationDecorator(number); number = new AsteriskDecorator(number); System.out.println(number.getNumber()); number = new PhoneNumber( "82675588" ); number = new CityDecorator(number); number = new AsteriskDecorator(number); System.out.println(number.getNumber()); number = new PhoneNumber( "82675588" ); number = new AsteriskDecorator(number); number = new CityDecorator(number); System.out.println(number.getNumber()); } }
package composite; import java.util.ArrayList; import java.util.Collection; import java.util.List; class View { } class ViewGroup extends View { private List<View> children = new ArrayList<View>(); public void add(View v) { children.add(v); } public Collection<View> getChildren() { return new ArrayList<View>(children); } } public class CompositeDemo { public static void main(String[] args) { ViewGroup vg1 = new ViewGroup(); ViewGroup vg2 = new ViewGroup(); ViewGroup vg3 = new ViewGroup(); ViewGroup vg4 = new ViewGroup(); ViewGroup vg5 = new ViewGroup(); // @formatter:off /* vg1 * |--vg2 * | |--vg4 * | |--vg5 * | * |--vg3 */ // @formatter:on vg1.add(vg2); vg1.add(vg3); vg2.add(vg4); vg2.add(vg5); } }
package observer; import java.util.Observable; import java.util.Observer; public class ObserverDemo { public static int SHARE_TYPE_NORMAL = 1 ; public static int SHARE_TYPE_EXCLUSIVE = 2 ; private CheckBox mCheckboxEnable = new CheckBox(); private SelectBox mSelectShareType = new SelectBox(); private TextBox mTextShareName = new TextBox(); private CheckBox mCheckboxReadOnly = new CheckBox(); private Label mLabelDescrpiton = new Label(); abstract class View extends Observable implements Observer { private boolean disabled = false ; public void setDisabled( boolean disabled) { this .disabled = disabled; } public boolean isDisabled() { return this .disabled; } } class SelectBox extends View { private int selected; public void setSelect( int index) { this .selected = index; setChanged(); notifyObservers(); } public int getSelect() { return selected; } @Override public void update(Observable observable, Object data) { if (mCheckboxEnable.isChecked()) { this .setDisabled( true ); } else { this .setDisabled( false ); } } } class TextBox extends View { private String text; public void setText(String text) { this .text = text; setChanged(); notifyObservers(); } public String getText() { return text; } @Override public void update(Observable observable, Object data) { if (mCheckboxEnable.isChecked()) { this .setDisabled( true ); } else { this .setDisabled( false ); } } } class CheckBox extends View { private boolean checked; public void setChecked( boolean checked) { this .checked = checked; setChanged(); notifyObservers(); } public boolean isChecked() { return checked; } @Override public void update(Observable observable, Object data) { if ( this == mCheckboxEnable) { return ; } if ( this == mCheckboxReadOnly) { if (mSelectShareType.getSelect() == SHARE_TYPE_NORMAL) { this .setDisabled( false ); } else if (mSelectShareType.getSelect() == SHARE_TYPE_EXCLUSIVE) { this .setChecked( true ); this .setDisabled( true ); } } } } class Label extends View { private String text; @Override public void update(Observable observable, Object data) { if (!mCheckboxEnable.isChecked()) { this .text = "Disabled" ; return ; } this .text = mSelectShareType.toString() + mTextShareName.toString() + mCheckboxReadOnly.toString(); } public String getText() { return text; } } public ObserverDemo() { mCheckboxEnable.addObserver(mSelectShareType); mCheckboxEnable.addObserver(mTextShareName); mCheckboxEnable.addObserver(mCheckboxReadOnly); mCheckboxEnable.addObserver(mLabelDescrpiton); mSelectShareType.addObserver(mCheckboxReadOnly); mSelectShareType.addObserver(mLabelDescrpiton); mTextShareName.addObserver(mCheckboxReadOnly); mTextShareName.addObserver(mLabelDescrpiton); } public static void main(String[] args) { } }
package state; class Activity { protected State state; abstract class State { abstract void next(); } class BootImageState extends State { @Override void next() { if (isFirstRun()) { state = new FinishState(); } else { showBootImage(); state = new AdState(); } } } class AdState extends State { @Override void next() { if (isAdReady()) { showAd(); state = new FinishState(); } else { state = new CoverStoryState(); } } } class CoverStoryState extends State { @Override void next() { if (isCoverStoryReady()) { showCoverStory(); } state = new FinishState(); } } class FinishState extends State { @Override void next() { state = null ; enterMainActivity(); } } private boolean isFirstRun() { return false ; } private void showBootImage(){} private boolean isAdReady() { return true ; } private void showAd() { } private boolean isCoverStoryReady() { return true ; } private void showCoverStory() { } public void enterMainActivity() { // MainActivity.start(); // this.finish(); } public void execute() { while (state != null ) { state.next(); } } } public class StateDemo { public static void main(String[] args) { Activity powerOn = new Activity(); powerOn.execute(); } }
package strategy; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; class Person { private final int id; private final String name; public Person( int id, String name) { this .id = id; this .name = name; } public int getId() { return id; } public String getName() { return name; } public String toString() { return "{" + id + ", " + name + "}" ; } } class PersonComparatorById implements Comparator<Person> { @Override public int compare(Person p0, Person p1) { return p0.getId() - p1.getId(); } } class PersonComparatorByName implements Comparator<Person> { @Override public int compare(Person p0, Person p1) { return p0.getName().compareTo(p1.getName()); } } public class StrategyDemo { public static void main(String[] args) { List<Person> persons = Arrays.asList( new Person( 80 , "Mick" ), new Person( 90 , "Racheal" ), new Person( 15 , "Jack" ), new Person( 21 , "Don" ), new Person( 93 , "Wislee" ), new Person( 65 , "Lucy" ), new Person( 70 , "Nazu" )); Collections.sort(persons, new PersonComparatorById()); System.out.println( "Sorted by ID : " + persons); Collections.sort(persons, new PersonComparatorByName()); System.out.println( "Sorted by Name : " + persons); } }
package responsibilitychain; import android.content.Intent; import android.net.ConnectivityManager; abstract class IntentHandler { private final IntentHandler nextHandler; public IntentHandler(IntentHandler nextHandler) { this .nextHandler = nextHandler; } abstract public boolean process(Intent intent); public void handle(Intent intent) { if (process(intent) && nextHandler != null ) { nextHandler.process(intent); } } } class ActionValidateHandler extends IntentHandler { public ActionValidateHandler(IntentHandler nextHandler) { super (nextHandler); } @Override public boolean process(Intent intent) { if (intent.getAction() == null ) { return false ; } return true ; } } class NetworkChangeHandler extends IntentHandler { public NetworkChangeHandler(IntentHandler nextHandler) { super (nextHandler); } @Override public boolean process(Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { // 处理网络变化逻辑 } return true ; } } class SaveIntentHandler extends IntentHandler { public SaveIntentHandler(IntentHandler nextHandler) { super (nextHandler); } @Override public boolean process(Intent intent) { save((Intent) intent.clone()); return true ; } private void save(Intent intent) { // 保存intent } } class Receiver { public void receive(Intent intent) { IntentHandler saveHandler = new SaveIntentHandler( null ); IntentHandler netHandler = new NetworkChangeHandler(saveHandler); IntentHandler actionHandler = new ActionValidateHandler(netHandler); actionHandler.handle(intent); } } public class ChainOfResponsibilityDemo { public static void main(String[] args) { new Receiver().receive( new Intent()); } }
package iterator; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import com.sina.news.bean.NewsItem; class NewsItemList implements Iterable<NewsItem> { private List<NewsItem> items = null ; public NewsItemList() { items = new ArrayList<NewsItem>(); } public void add(NewsItem item) { items.add(item); } public void addAll(Collection<NewsItem> c) { items.addAll(c); } @Override public Iterator<NewsItem> iterator() { return new Iterator<NewsItem>() { private int index = - 1 ; @Override public boolean hasNext() { return index + 1 < items.size(); } @Override public NewsItem next() { return items.get(++index); } @Override public void remove() { items.remove(index); } }; } } public class IteratorDemo { public static void main(String[] args) { NewsItemList itemList = new NewsItemList(); itemList.add( new NewsItem()); itemList.add( new NewsItem()); itemList.add( new NewsItem()); itemList.add( new NewsItem()); itemList.add( new NewsItem()); Iterator<NewsItem> it = itemList.iterator(); while (it.hasNext()) { System.out.println(it.next().hashCode()); } // for(NewsItem item : itemList){ // System.out.println(item.hashCode()); // } } }
转载于:https://www.cnblogs.com/xinmengwuheng/p/7605443.html