History variables: Difference between revisions
Content added Content deleted
(add swift) |
(AspectJ version (java 7 required).) |
||
Line 188: | Line 188: | ||
<pre>one oneone three |
<pre>one oneone three |
||
14</pre> |
14</pre> |
||
=={{header|AspectJ}}== |
|||
AspectJ implementation for Java 7. |
|||
Type of the history variable (Java class): |
|||
<lang java>public class HistoryVariable |
|||
{ |
|||
public HistoryVariable(final Object v) |
|||
{ |
|||
super(); |
|||
value = v; |
|||
} |
|||
public void update(final Object v) |
|||
{ |
|||
value = v; |
|||
} |
|||
public Object undo() |
|||
{ |
|||
return value; |
|||
} |
|||
@Override |
|||
public String toString() |
|||
{ |
|||
return value.toString(); |
|||
} |
|||
public void dispose() |
|||
{ |
|||
} |
|||
private Object value; |
|||
}</lang> |
|||
Aspect (HistoryHandling.aj): |
|||
<lang java>import java.util.Deque; |
|||
import java.util.HashMap; |
|||
import java.util.LinkedList; |
|||
import java.util.Map; |
|||
public privileged aspect HistoryHandling |
|||
{ |
|||
before() : execution(HistoryVariable.new(..)) |
|||
{ |
|||
history.put((HistoryVariable) thisJoinPoint.getTarget(), new LinkedList<>()); |
|||
} |
|||
after() : execution(void HistoryVariable.dispose()) |
|||
{ |
|||
history.remove(thisJoinPoint.getTarget()); |
|||
} |
|||
before(Object v) : execution(void HistoryVariable.update(Object)) && args(v) |
|||
{ |
|||
final HistoryVariable hv = (HistoryVariable) thisJoinPoint.getThis(); |
|||
history.get(hv).add(hv.value); |
|||
} |
|||
after() : execution(Object HistoryVariable.undo()) |
|||
{ |
|||
final HistoryVariable hv = (HistoryVariable) thisJoinPoint.getThis(); |
|||
final Deque<Object> q = history.get(hv); |
|||
if (!q.isEmpty()) |
|||
hv.value = q.pollLast(); |
|||
} |
|||
String around() : this(HistoryVariable) && execution(String toString()) |
|||
{ |
|||
final HistoryVariable hv = (HistoryVariable) thisJoinPoint.getThis(); |
|||
final Deque<Object> q = history.get(hv); |
|||
if (q == null) |
|||
return "<disposed>"; |
|||
else |
|||
return "current: "+ hv.value + ", previous: " + q.toString(); |
|||
} |
|||
private Map<HistoryVariable, Deque<Object>> history = new HashMap<>(); |
|||
}</lang> |
|||
Usage: |
|||
<lang java>public final class Main |
|||
{ |
|||
public static void main(final String[] args) |
|||
{ |
|||
HistoryVariable hv = new HistoryVariable("a"); |
|||
hv.update(90); |
|||
hv.update(12.1D); |
|||
System.out.println(hv.toString()); |
|||
System.out.println(hv.undo()); |
|||
System.out.println(hv.undo()); |
|||
System.out.println(hv.undo()); |
|||
System.out.println(hv.undo()); |
|||
System.out.println(hv.toString()); |
|||
hv.dispose(); |
|||
System.out.println(hv.toString()); |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre>current: 12.1, previous: [a, 90] |
|||
12.1 |
|||
90 |
|||
a |
|||
a |
|||
current: a, previous: [] |
|||
<disposed></pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |