Some collection of design ideas (1)

About TextBox content is automatically converted design:

First, define the interface

public interface IConverter {

    string Convert(string value);

}

Then define specific conversion type, such as the amount type class values ​​are automatically converted comma

public class CurrentMoneyConverter : IConverter {

    public string Convert (string value) {...} // achieve specific conversion logic

}

Save the definition of the object controls need to convert container class

public class ActiveConverter {

    // save the additional control and switching patterns corresponding to the
    private Dictionary <Control, Queue <IConverter >> dic = new Dictionary <Control, Queue <IConverter >> ();

    // The method requires additional conversion and conversion mode control
    public void AddConverter (Control Control, the IConverter Converter) {
        IF (dic.ContainsKey (Control)) {
            IF (DIC [Control] .Contains (Converter) == to false) {
                DIC [Control] .Enqueue (Converter);
            }
        } the else {
            Queue <the IConverter> = new new Queue Queue <the IConverter> ();
            queue.Enqueue (Converter);
            dic.Add (Control, Queue);
            control.Leave the EventHandler + = new new (this.DoConversion);
        }
    }

    // 转换事件
    private void DoConversion(object sender, EventArgs e) {
        Control control;
        if (sender is Control) {
            control = (Control)sender;
        } else {
            return;
        }
        Queue<IConverter> queue;
        if (dic.ContainsKey(control)) {
            queue = dic[control];
        } else {
            return;
        }
        foreach (IConverter converter in queue) {
            try {
                control.Text = converter.Convert(control.Text);
            } catch {
                // TODO
            }
        }
    }

    public ActiveConverter() {
        return;
    }
}

Finally, the definition on the screen ActiveConverter instance class, the initialization screen when instantiated, additional controls and the need to convert

 this.activeConverter.AddConverter(this.tbxA, new CurrentMoneyConverter());
this.activeConverter.AddConverter(this.tbxB, new AlphanumericOnlyConverter());

 

This design concept focuses on simplifying picture class design, it only focused on data representation.

Reproduced in: https: //my.oschina.net/cjkall/blog/195889

Guess you like

Origin blog.csdn.net/weixin_33756418/article/details/91756075